Microsoft KB Archive/317662

= HOW TO: Load and Save XML by Using DOM in .NET Framework with Visual C# .NET =

Article ID: 317662

Article Last Modified on 9/22/2003

-

APPLIES TO


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

-



This article was previously published under Q317662



For a Microsoft Visual Basic .NET version of this article, see 317661.

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 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:    Principle of Relativity Albert Einstein Physics   Cosmos</Title> Carl Sagan</Author> Cosmology</Genre> </Book> </Collection> </li> <li>Create a new Visual C# .NET Console application project.</li> <li> 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(&quot;Q317662.xml&quot;);

// 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(&quot;Q317662.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/Q317662.xml&quot;);

// 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(&quot;Q317662.xml&quot;); 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(&quot;<Collection>Priciple 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;\n{0}\n&quot;, doc.OuterXml); }        catch(XmlException xmlEx)   // Handle the XML exceptions here. {           Console.WriteLine(&quot;{0}&quot;, xmlEx.Message); }        catch(Exception ex)         // Handle the generic exceptions here. {           Console.WriteLine(&quot;{0}&quot;, ex.Message); }        finally {           // Finalize here. }     }   }

} </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 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>Priciple 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 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. <ol> <li>Create a new Visual C# .NET Console application project.</li> <li> 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(&quot;Q317662.xml&quot;);

// Save the XML to a file. doc.Save(&quot;Q317662_File.xml&quot;);

// 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(&quot;Q317662_Writer.xml&quot;, Encoding.Unicode); wrtr.WriteRaw(xmlStr); wrtr.Close; }        catch(XmlException xmlEx)   // Handle the XML exceptions here. {           Console.WriteLine(&quot;{0}&quot;, xmlEx.Message); }        catch(Exception ex)         // Handle the generic exceptions here. {           Console.WriteLine(&quot;{0}&quot;, ex.Message); }        finally {           // Finalize here. }     }   }

} </li> <li>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.</li> <li>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.</li></ol>

back to the top

<div class="references_section">