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:
<?xml version='1.0' encoding='ISO-8859-1'?>
<Collection>
<Book>
<Title>Principle of Relativity</Title>
<Author>Albert Einstein</Author>
<Genre>Physics</Genre>
</Book>
<Book>
<Title>Cosmos</Title>
<Author>Carl Sagan</Author>
<Genre>Cosmology</Genre>
</Book>
</Collection>
- Create a new Visual Basic .NET Console application project.
- 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("Q317661.xml")
' 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("Q317661.xml", 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("http://localhost/xmltest/Q317661.xml")
' Load the XML data from a reader object.
' Ignore the white spaces.
doc.PreserveWhitespace = False
Dim rdr As New XmlTextReader("Q317661.xml")
doc.Load(rdr)
' Load the XML strings.
doc.LoadXml("<Collection><Book><Title>Principle of Relativity</Title>" & _
"<Author>Albert Einstein</Author>" & _
"<Genre>Physics</Genre></Book></Collection>")
' Display the content of the DOM document.
Console.Write("{0}", vbNewLine & doc.OuterXml & vbNewLine)
' Handle the XML exceptions here.
Catch xmlex As XmlException
Console.WriteLine("{0}", xmlex.Message)
' Handle the generic exceptions here.
Catch ex As Exception
Console.WriteLine("{0}", ex.Message)
Finally
' Add code here to finalize.
End Try
End Sub
End Module
- 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.
- 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><Book><Title>Principle of Relativity</Title><Author>Albert Einstein</
Author><Genre>Physics</Genre></Book></Collection>
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.
- Create a new Visual Basic .NET Console application project.
- 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("Q317661.xml")
' Save the XML to a file.
doc.Save("Q317661_File.xml")
' 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("Q317661_Writer.xml", Encoding.Unicode)
wrtr.WriteRaw(xmlStr)
wrtr.Close()
' Handle the XML exceptions here.
Catch xmlex As XmlException
Console.WriteLine("{0}", xmlex.Message)
' Handle the generic exceptions here.
Catch ex As Exception
Console.WriteLine("{0}", ex.Message)
Finally
' Add code here to finalize.
End Try
End Sub
End Module
- 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.
- 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.
back to the top