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
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 C# .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 Definintion (DTD), an XML Data-Reduced (XDR) or an XML Schema Definition Language (XSD) schema is done through the
System.Xml.XmlValidatingReader class. If validataion 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 Q317662.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 C# .NET Console application project.
- Replace the code in the Class1.cs file with the following code. This example shows how to read XML data from a file, a URL, a Stream and an XmlTextReader.
using System;
using System.Xml;
using System.IO;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
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.
XmlDocument doc = new XmlDocument();
// Load the XML data from a file.
// This code assumes that the XML file is in the same folder.
doc.Load("Q317662.xml");
// Load the XML data from a file stream.
// You can also use other I/O streams in the same way with the
// Load method.
FileStream fileStrm = new FileStream("Q317662.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/Q317662.xml");
// Load the XML data from a reader object.
// Ignore the white spaces.
doc.PreserveWhitespace = false;
// Read the XML by using XmlTextReader.
XmlTextReader rdr = new XmlTextReader("Q317662.xml");
rdr.MoveToContent(); // Move to the content nodes.
rdr.Read(); // Start reading.
rdr.Skip(); // Skip the root.
rdr.Skip(); // Skip the first content node.
doc.Load(rdr); // Read the second node data into DOM.
// To load the entire data, pass in the reader object when its
// state is ReadState.Initial.
// To do this in the aforementioned code section, comment out
// the Skip and MoveToContent method calls.
// Load the XML strings.
doc.LoadXml("<Collection><Book><Title>Priciple of Relativity</Title>" +
"<Author>Albert Einstein</Author>" +
"<Genre>Physics</Genre></Book></Collection>");
// Display the content of the DOM document.
Console.Write("\n{0}\n", doc.OuterXml);
}
catch(XmlException xmlEx) // Handle the XML exceptions here.
{
Console.WriteLine("{0}", xmlEx.Message);
}
catch(Exception ex) // Handle the generic exceptions here.
{
Console.WriteLine("{0}", ex.Message);
}
finally
{
// Finalize here.
}
}
}
}
- 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 Q317662.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>Priciple 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 documention.
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 C# .NET Console application project.
- Replace the code in the Class1.cs file with the following code. This example shows how to save XML data to a file, a Stream, and XmlTextWriter.
using System;
using System.Xml;
using System.IO;
using System.Text;
namespace ConsoleApplication2
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
// Create an XML document instance and load the XML data.
XmlDocument doc = new XmlDocument();
// This code assumes that the XML file is in the same folder.
doc.Load("Q317662.xml");
// Save the XML to a file.
doc.Save("Q317662_File.xml");
// Save the XML to a memory stream.
MemoryStream memStream = new MemoryStream();
ASCIIEncoding AE = new ASCIIEncoding();
string xmlStr = doc.DocumentElement.OuterXml;
memStream.Write(AE.GetBytes(xmlStr), 0, xmlStr.Length);
// Use the data from the stream here.
memStream.Close();
// Save the XML to XmlWriter with Unicode encoding.
// Preserve the whitespace.
doc.PreserveWhitespace = true;
XmlTextWriter wrtr = new XmlTextWriter("Q317662_Writer.xml", Encoding.Unicode);
wrtr.WriteRaw(xmlStr);
wrtr.Close();
}
catch(XmlException xmlEx) // Handle the XML exceptions here. {
Console.WriteLine("{0}", xmlEx.Message);
}
catch(Exception ex) // Handle the generic exceptions here.
{
Console.WriteLine("{0}", ex.Message);
}
finally
{
// Finalize here.
}
}
}
}
- Read the inline comments to understand the functionality of the code. Make sure that the Q317662.xml file is in the same folder as the executable file. Compile and run the application.
- Examine the output files (Q317662_File.xml and Q317662_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