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

Article translations Article translations
Article ID: 317662 - View products that this article applies to.
This article was previously published under Q317662
Expand all | Collapse all

On This Page

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.

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

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:
  1. 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>
    					
  2. Create a new Visual C# .NET Console application project.
  3. 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.
             }
          }
       }
    
    }
  4. 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.
  5. 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>
    					

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.
  1. Create a new Visual C# .NET Console application project.
  2. 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.
             }
          }
       }
    
    }
  3. 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.
  4. 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.

REFERENCES

For additional information, visit the following Microsoft Web sites:
System.Xml Namespace
http://msdn.microsoft.com/en-us/library/system.xml(VS.71).aspx

XML
http://msdn.microsoft.com/xml
For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:
313824 INFO: Roadmap for Programming XML with the DOM-Model Parser in the .NET Framework
313651 INFO: Roadmap for XML in the .NET Framework

Properties

Article ID: 317662 - Last Review: September 22, 2003 - Revision: 3.4
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
Keywords: 
kbbcl kbhowtomaster KB317662

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com