Microsoft KB Archive/317661

= How to load and save XML by using DOM in .NET Framework with Visual Basic .NET =

Article ID: 317661

Article Last Modified on 3/28/2005

-

APPLIES TO


 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft .NET Framework 1.0
 * Microsoft .NET Framework 1.1

-



This article was previously published under Q317661





For a Microsoft Visual C# .NET version of this article, see 317662.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Xml
 * System.IO
 * System.Text

IN THIS TASK
SUMMARY
 * Requirements
 * How to Load XML Documents
 * How to Save XML Documents

REFERENCES



SUMMARY
Use this step-by-step guide to learn how to programmatically load and save Extensible Markup Language (XML) documents by using the System.Xml.XmlDocument class. This class is compliant with the World Wide Web Consortium Document Object Model (DOM) Level 1 and Level 2 core standards. Furthermore, System.Xml.XmlDocument implements the core XML DOM parser in Microsoft .NET Framework.

XmlDocument is derived from the System.Xml.XmlNode class, so it inherits several properties and methods from the XmlNode class.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Windows XP, Microsoft Windows 2000, or Microsoft Windows NT 4.0 with Service Pack 6a
 * Microsoft Data Access Components (MDAC) 2.6 or later
 * Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:
 * Visual Basic .NET syntax
 * XML and the related standards

back to the top

How to Load XML Documents
The Load and LoadXml methods of the XmlDocument class load XML data. The Load method is overloaded and provides ways to load XML documents from different resources, such as a URL or a Stream. For more information about the overloads, see the Microsoft .NET Framework Software Development Kit (SDK) documentation.

You can also use the LoadXml method to load XML strings and fragments. The Load method preserves white space by default and the LoadXml method does not. If you use either of these methods, you can use the PreserveWhitespace Boolean property to control how white space is handled.

In the Microsoft .NET Framework, validation of XML documents against a Document Type Definition (DTD), an XML Data-Reduced (XDR) or an XML Schema Definition Language (XSD) schema is done through the System.Xml.XmlValidatingReader class. If validation is required, the data is loaded into DOM, an XmlValidatingReader class is constructed and passed to the Load method.

The following sample code shows how to use these methods to load XML data from different resources:   In Notepad or another text editor, type or paste the following information, and then save the file as Q317661.xml:    Principle of Relativity Albert Einstein Physics   Cosmos</Title> Carl Sagan</Author> Cosmology</Genre> </Book> </Collection> </li> <li>Create a new Visual Basic .NET Console application project.</li> <li> Replace the code in the Module1.vb file with the following code. This sample shows how to read XML data from a file, a URL, a Stream, and an XmlTextReader. Imports System.Xml Imports System.IO

Module Module1

Sub Main

Try ' Create an XML document instance. ' The same instance of DOM is used through out this code; this ' may or may not be the actual case. Dim doc As XmlDocument = New XmlDocument

' Load the XML data from a file. ' This code assumes that the XML file is in the same folder. doc.Load(&quot;Q317661.xml&quot;)

' Load the XML data from a file stream. ' You can use other I/O streams in the same way with the Load ' method. Dim fileStrm As FileStream = New IO.FileStream(&quot;Q317661.xml&quot;, FileMode.Open) ' New content replaces older content because the same DOM is         ' used. doc.Load(fileStrm) ' Use DOM to manipulate the XML data here. ' Close any Streams once they are used. fileStrm.Close

' Load the XML data from a URL. ' Make sure that the URL points to a correct XML resource. doc.Load(&quot;http://localhost/xmltest/Q317661.xml&quot;)

' Load the XML data from a reader object. ' Ignore the white spaces. doc.PreserveWhitespace = False Dim rdr As New XmlTextReader(&quot;Q317661.xml&quot;) doc.Load(rdr)

' Load the XML strings. doc.LoadXml(&quot;<Collection>Principle of Relativity</Title>&quot; & _                    &quot;Albert Einstein</Author>&quot; & _                     &quot;Physics</Genre></Book></Collection>&quot;)

' Display the content of the DOM document. Console.Write(&quot;{0}&quot;, vbNewLine & doc.OuterXml & vbNewLine)

' Handle the XML exceptions here. Catch xmlex As XmlException Console.WriteLine(&quot;{0}&quot;, xmlex.Message) ' Handle the generic exceptions here. Catch ex As Exception Console.WriteLine(&quot;{0}&quot;, ex.Message) Finally ' Add code here to finalize. End Try

End Sub

End Module </li> <li>Read the inline comments to understand the functionality of the code. Make sure that the XML resource files point to the correct folder, URL, and so on.</li> <li> Compile and run the application.

Note that the Q317661.xml file should be in the same folder as the executable file. or you must modify the file path in the code.

The output appears similar to the following: <Collection>Principle of Relativity</Title>Albert Einstein</ Author>Physics</Genre></Book></Collection> </li></ol>

back to the top

How to Save XML Documents
The Save method of the XmlDocument saves XML data. The Save method is overloaded and saves XML documents to a file, a Stream, or writer objects. For additional information about overloads, see the Microsoft .NET Framework SDK documentation.

White space is preserved only if you set the PreserveWhitespace Boolean property to true. Also, you can use the WriteContentTo and the WriteTo methods to write XML data to XmlWriter. Their functionality is equivalent to the InnerXml and OuterXml properties. <ol> <li>Create a new Visual Basic .NET Console application project.</li> <li> Replace the code in Module1.vb file with the following. This example shows how to save XML data to a file, a Stream, and XmlTextWriter. Imports System.Xml Imports System.IO Imports System.Text

Module Module1

Sub Main

Try ' Create an XML document instance and load the XML data. Dim doc As XmlDocument = New XmlDocument ' This code assumes that the XML file is in the same folder. doc.Load(&quot;Q317661.xml&quot;)

' Save the XML to a file. doc.Save(&quot;Q317661_File.xml&quot;)

' Save the XML to a memory stream. Dim memStream As New MemoryStream Dim AE As New ASCIIEncoding Dim xmlStr As String = doc.DocumentElement.OuterXml memStream.Write(AE.GetBytes(xmlStr), 0, xmlStr.Length) ' Use the data from the stream here. memStream.Close

' Save the XML to an XmlWriter with Unicode encoding. ' Preserve the white space. doc.PreserveWhitespace = True Dim wrtr As New XmlTextWriter(&quot;Q317661_Writer.xml&quot;, Encoding.Unicode) wrtr.WriteRaw(xmlStr) wrtr.Close

' Handle the XML exceptions here. Catch xmlex As XmlException Console.WriteLine(&quot;{0}&quot;, xmlex.Message) ' Handle the generic exceptions here. Catch ex As Exception Console.WriteLine(&quot;{0}&quot;, ex.Message) Finally ' Add code here to finalize. End Try

End Sub

End Module

</li> <li>Read the in-line comments to understand the functionality of the code. Make sure that the Q317661.xml file is in the same folder as the executable file. Compile and run the application.</li> <li>Examine the output files (Q317661_File.xml and Q317661_Writer.xml) which are created in the same folder as the executable file. Both should contain the same data except that the data in the second file will be in Unicode encoding format.</li></ol>

back to the top

<div class="references_section">