Microsoft KB Archive/317666

From BetaArchive Wiki

Article ID: 317666

Article Last Modified on 9/24/2003



APPLIES TO

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



This article was previously published under Q317666

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

This article refers to the following Microsoft .NET Framework Class Library namespaces:

  • System.Xml
  • System.Text

IN THIS TASK

SUMMARY

REFERENCES

SUMMARY

This step-by-step article describes how to use the System.Xml.XmlDocument class and the related classes to programmatically modify XML documents.

XML content can be classified broadly into a collection of nodes and attributes of the nodes. You can modify the content by modifying the nodes or the attributes. The System.Xml.XmlDocument class implements the core XML Document Object Model (DOM) parser of the Microsoft .NET Framework. This class is compliant with the World Wide Web Consortium (W3C) Document Object Model (DOM) Level 1 and Level 2 Core standards. You can use the DOM model implementation to modify the content of XML documents; for example, you can insert, update, or delete data.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:

  • Microsoft Windows XP, Windows 2000, or Windows NT 4.0 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

Methods and Properties of System.Xml Classes

The following list describes several methods and properties of System.Xml classes. For more information, see the Microsoft .NET Framework Software Development Kit (SDK) documentation.

  • Update XML data:


Use the InnerText and the InnerXml properties of classes such as XmlDocument, XmlElement, or XmlAttribute to modify the content. Because these classes are derived from the System.Xml.XmlNode class, these classes inherit several properties and methods from the XmlNode class. InnerXml provides access to the content including the markup. You can use the Value property to set the value of a node; what is modified depends on the type of the node. You can use the Prefix property to set the namespace prefix of a node.

  • Add new XML data:


Use the AppendChild and the PrependChild methods to add a node to the end or to the beginning of the children list. Similarly, you can use the InsertAfter method or the InsertBefore method to add a node after or before the current node, respectively. Additionally, you can use methods of the XmlDocument class that start with the Create prefix, such as CreateElement, CreateAttribute, and CreateWhitespace, to create new content.

Typically, you create the required elements and then add the new elements to the existing XML data. Instead of creating all new content, you can use the Clone method or the CloneNode method to copy existing nodes, and then modify the data before you add the modified nodes to the tree as new content.

  • Delete XML data:


You can use the RemoveChild method of the XmlDocument or the XmlElement class to remove a specific child node or attribute. You can use the RemoveAll method of XmlDocument or XmlElement to remove all of the child nodes or attributes. You can delete attributes by using one of the following methods of XmlElement:

    • RemoveAllAttributes
    • RemoveAttribute
    • RemoveAttributeAt
    • RemoveAttributeNode

NOTE: Before you delete or modify a node or an attribute, you may have to locate or to select the required node or nodes. The XmlDocument class provides several methods and properties to locate nodes. For additional information, click the article number below to view the article in the Microsoft Knowledge Base:

317664 HOW TO: Access XML Data Using DOM in .NET Framework with Visual C# .NET


back to the top

Create the Visual C# .NET Sample

The following step-by-step code sample demonstrates how to use some of the methods that are described in this article to modify XML data:

  1. In Notepad or a similar text editor, create a new XML file with the following data, and then save the file as C:\Q317666.xml:

    <?xml version='1.0' encoding='ISO-8859-1'?>
    <Collection>
       <Book Id='1'>
          <Title>Principle of Relativity</Title>
          <Author>Albert Einstein</Author>
          <Genre>Physics</Genre>
       </Book>
       <Book Id='2'>
          <Title>Cosmos</Title>
          <Author>Carl Sagan</Author>
          <Genre>Cosmology</Genre>
       </Book>
    </Collection>
                        
  2. Follow these steps to create a new Visual C# .NET Console Application project:
    1. Start Microsoft Visual Studio .NET.
    2. On the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click Console Application under Templates.
  3. Replace the code in the Class1.cs file with the following code:

    using System;
    using System.Xml;
    using System.Text;
    
    namespace ConsoleApplication1
    {
       class Class1
       {
          [STAThread]
          static void Main(string[] args)
          {
             try
             {
                // Create an XML document instance, and load XML data.
                XmlDocument doc  = new XmlDocument();
                doc.Load("Q317666.xml");                      // This code assumes that the XML file is in the same folder.
    
                // I. Modification
                // 1. Increment all of the Book Id attribute values by 100.
                XmlNodeList nodeList = doc.SelectNodes("//Book");
                foreach (XmlNode node in nodeList)
                   node.Attributes["Id"].Value = (Int32.Parse(node.Attributes["Id"].Value) + 100).ToString();
    
                // 2. Change the book titles to uppercase letters.
                foreach (XmlNode node in nodeList)
                   node.FirstChild.InnerText = (node.FirstChild.InnerText).ToUpper();
    
                // 3. Modify the XML declaration instruction to have Unicode encoding.
                XmlDeclaration decl = (XmlDeclaration) doc.FirstChild;
                decl.Encoding = "UTF-16";
    
                // II. Addition
                // 1. Create a new Book element.
                XmlElement newElem = doc.CreateElement("Book");
    
                // Add the Id attribute.
                XmlAttribute newAttr = doc.CreateAttribute("Id");
                newAttr.Value = "103";
                newElem.Attributes.Append(newAttr);
    
                // Create the child nodes. This code demonstrates various ways to add them.
                newElem.InnerXml = "<Title></Title><Author></Author>";
                XmlText txtNode = doc.CreateTextNode("A BRIEF HISTORY OF TIME");
                newElem.FirstChild.AppendChild(txtNode);
                newElem.AppendChild(doc.CreateWhitespace("\r\n")); // Linefeed
                newElem["Author"].InnerText = "Stephen Hawking";
    
                // 2.  Add the new element to the end of the book list.
                doc.DocumentElement.AppendChild(newElem);
    
                // III. Deletion
                // 1. Remove the Genre nodes from Book elements.
                foreach (XmlNode node in nodeList)
                   node.RemoveChild(node.SelectSingleNode("Genre"));
    
                // Display the output in Debug window.
                System.Diagnostics.Debug.Write("{0}\n", doc.OuterXml);
    
                // 2. Save the modified XML to a file in Unicode format.
                doc.PreserveWhitespace = true;
                XmlTextWriter wrtr = new XmlTextWriter("Q317666_Out.xml", Encoding.Unicode);
                doc.WriteTo(wrtr);
                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);
             }
          }
       }
    }
                            

    This code performs the following tasks:

    • Loads the XML document from a file that represents a collection of Books.
    • Modifies some of the content.
    • Creates and adds a new Book element.
    • Deletes one of the child nodes from all of the Book nodes.
    • Saves the modified data as a new XML file.


  4. Read the inline comments to understand the functionality of the code.
  5. Compile and run the application. Notice that the Q317666.xml file is in the same folder as the executable file. You can modify the file path in the code to change this.
  6. Open the C:\Q317666_Out.xml file in Microsoft Internet Explorer. The output appears similar to the following:
      <?xml version="1.0" encoding="UTF-16" ?> 
    - <Collection>
      - <Book Id="101">
          <Title>PRINCIPLE OF RELATIVITY</Title> 
          <Author>Albert Einstein</Author> 
        </Book>
      - <Book Id="102">
          <Title>COSMOS</Title> 
          <Author>Carl Sagan</Author> 
        </Book>
      - <Book Id="103">
          <Title>A BRIEF HISTORY OF TIME</Title> 
          <Author>Stephen Hawking</Author> 
      </Book>
      </Collection>
                            

back to the top

REFERENCES

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


For additional information, visit the following Microsoft Web sites:

back to the top

Keywords: kbhowtomaster kbbcl KB317666