Microsoft KB Archive/317666

= HOW TO: Modify XML Data by Using DOM in .NET Framework with Visual C# .NET =

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
 * Requirements
 * Methods and Properties of System.Xml Classes
 * Create the Visual C# .NET Sample

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:   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:    Principle of Relativity Albert Einstein Physics   Cosmos</Title> Carl Sagan</Author> Cosmology</Genre> </Book> </Collection> </li> <li>Follow these steps to create a new Visual C# .NET Console Application project: <ol style="list-style-type: lower-alpha;"> <li>Start Microsoft Visual Studio .NET.</li> <li>On the File menu, point to New, and then click Project.</li> <li>In the New Project dialog box, click Visual C# Projects under Project Types, and then click Console Application under Templates.</li></ol> </li> <li> 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(&quot;Q317666.xml&quot;);                     // 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(&quot;//Book&quot;); foreach (XmlNode node in nodeList) node.Attributes[&quot;Id&quot;].Value = (Int32.Parse(node.Attributes[&quot;Id&quot;].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 = &quot;UTF-16&quot;;

// II. Addition // 1. Create a new Book element. XmlElement newElem = doc.CreateElement(&quot;Book&quot;);

// Add the Id attribute. XmlAttribute newAttr = doc.CreateAttribute(&quot;Id&quot;); newAttr.Value = &quot;103&quot;; newElem.Attributes.Append(newAttr);

// Create the child nodes. This code demonstrates various ways to add them. newElem.InnerXml = &quot;</Title></Author>&quot;; XmlText txtNode = doc.CreateTextNode(&quot;A BRIEF HISTORY OF TIME&quot;); newElem.FirstChild.AppendChild(txtNode); newElem.AppendChild(doc.CreateWhitespace(&quot;\r\n&quot;)); // Linefeed newElem[&quot;Author&quot;].InnerText = &quot;Stephen Hawking&quot;;

// 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(&quot;Genre&quot;));

// Display the output in Debug window. System.Diagnostics.Debug.Write(&quot;{0}\n&quot;, doc.OuterXml);

// 2. Save the modified XML to a file in Unicode format. doc.PreserveWhitespace = true; XmlTextWriter wrtr = new XmlTextWriter(&quot;Q317666_Out.xml&quot;, Encoding.Unicode); doc.WriteTo(wrtr); 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); }     }   } } This code performs the following tasks: <ul> <li>Loads the XML document from a file that represents a collection of Books.</li> <li>Modifies some of the content.</li> <li>Creates and adds a new Book element.</li> <li>Deletes one of the child nodes from all of the Book nodes.</li> <li>Saves the modified data as a new XML file.</li></ul>

</li> <li>Read the inline comments to understand the functionality of the code.</li> <li>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.</li> <li>Open the C:\Q317666_Out.xml file in Microsoft Internet Explorer. The output appears similar to the following:

<pre class="fixed_text"> <?xml version=&quot;1.0&quot; encoding=&quot;UTF-16&quot; ?> - <Collection> - <Book Id=&quot;101&quot;> PRINCIPLE OF RELATIVITY</Title> Albert Einstein</Author> </Book> - <Book Id=&quot;102&quot;> COSMOS</Title> Carl Sagan</Author> </Book> - <Book Id=&quot;103&quot;> A BRIEF HISTORY OF TIME</Title> Stephen Hawking</Author> </Book> </Collection>

</li></ol>

back to the top

<div class="references_section">