Microsoft KB Archive/317665

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

Article ID: 317665

Article Last Modified on 9/16/2003

-

APPLIES TO


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

-



This article was previously published under Q317665



For a Microsoft Visual C# .NET version of this article, see 317666.

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 Basic .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 Extensible Markup Language (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 attributes. The System.Xml.XmlDocument class implements the core XML DOM parser of the .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, Microsoft Windows 2000, or Microsoft Windows NT 4.0 Service Pack 6a
 * Microsoft Data Access Components 2.6 (MDAC) or later
 * Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:
 * Visual Basic .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. These classes are derived from the System.Xml.XmlNode class, so 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. Use the Prefix property to set the namespace prefix of a node. What you modify depends on the type of the 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 XmlDocument that begin with the Create prefix, such as CreateElement, CreateAttribute, and CreateWhitespace, to construct new content.

Typically, you construct 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 and add the modified nodes to the tree as new content.
 * Delete XML data:

Use the RemoveChild method of XmlDocument or XmlElement to remove a specific child node or attribute. 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 attribute, you may need to locate or 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:

317663 HOW TO: Access XML Data by Using DOM in .NET Framework with Visual Basic .NET

back to the top

Create the Visual Basic .NET Sample
The following step-by-step code example 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:\Q317665.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 Basic .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 Basic Projects under Project Types, and then click Console Application under Templates.</li></ol> </li> <li> Replace the code in Module1.vb with the following code: Imports System.Xml Imports System.Text

Module Module1

Sub Main

Try

' Create an Xml document instance and load XML data. Dim doc As XmlDocument = New XmlDocument doc.Load(&quot;C:\Q317665.xml&quot;)

' I. Modification ' 1. Increment all the Book Id attribute values by 100. Dim nodeList As XmlNodeList = doc.SelectNodes(&quot;//Book&quot;) Dim node As XmlNode For Each node In nodeList node.Attributes(&quot;Id&quot;).Value = node.Attributes(&quot;Id&quot;).Value + 100 Next

' 2. Update the capitalization of the book titles. For Each node In nodeList node.FirstChild.InnerText = (node.FirstChild.InnerText).ToUpper Next

' 3. Modify the XML declaration instruction to have Unicode encoding. Dim decl As XmlDeclaration = doc.FirstChild decl.Encoding = &quot;UTF-16&quot;

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

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

' Create the child nodes. The following example shows various ways to add child nodes. newElem.InnerXml = &quot;</Title></Author>&quot; Dim txtNode As XmlText = doc.CreateTextNode(&quot;A BRIEF HISTORY OF TIME&quot;) newElem.FirstChild.AppendChild(txtNode) newElem.AppendChild(doc.CreateWhitespace(ControlChars.CrLf)) newElem.Item(&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. For Each node In nodeList node.RemoveChild(node.SelectSingleNode(&quot;Genre&quot;)) Next

' Display the output in the Debug window. Diagnostics.Debug.Write(&quot;{0}&quot;, doc.OuterXml & vbNewLine)

' 2. Save the modified XML to a file in Unicode format. doc.PreserveWhitespace = True Dim wrtr As XmlTextWriter = New XmlTextWriter(&quot;C:\Q317665_Out.xml&quot;, Encoding.Unicode) doc.WriteTo(wrtr) wrtr.Close Console.WriteLine(&quot;C:\Q317665_Out.xml is created&quot;) Console.ReadLine

Catch xmlex As XmlException                 ' Handle the Xml Exceptions here. Console.WriteLine(&quot;{0}&quot;, xmlex.Message) Catch ex As Exception                       ' Handle the generic Exceptions here. Console.WriteLine(&quot;{0}&quot;, ex.Message) End Try

End Sub

End Module 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. Compile and run the application. Use Microsoft Internet Explorer to open the C:\Q317665_Out.xml file. The output should resemble 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">