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
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
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
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:
<?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>
- Follow these steps to create a new Visual Basic .NET Console Application project:
- Start Microsoft Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Console Application under Templates.
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("C:\Q317665.xml") ' I. Modification ' 1. Increment all the Book Id attribute values by 100. Dim nodeList As XmlNodeList = doc.SelectNodes("//Book") Dim node As XmlNode For Each node In nodeList node.Attributes("Id").Value = node.Attributes("Id").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 = "UTF-16" ' II. Addition ' 1. Create a new Book element. Dim newElem As XmlElement = doc.CreateElement("Book") ' Add the Id attribute. Dim newAttr As XmlAttribute = doc.CreateAttribute("Id") newAttr.Value = "103" newElem.Attributes.Append(newAttr) ' Create the child nodes. The following example shows various ways to add child nodes. newElem.InnerXml = "<Title></Title><Author></Author>" Dim txtNode As XmlText = doc.CreateTextNode("A BRIEF HISTORY OF TIME") newElem.FirstChild.AppendChild(txtNode) newElem.AppendChild(doc.CreateWhitespace(ControlChars.CrLf)) newElem.Item("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. For Each node In nodeList node.RemoveChild(node.SelectSingleNode("Genre")) Next ' Display the output in the Debug window. Diagnostics.Debug.Write("{0}", doc.OuterXml & vbNewLine) ' 2. Save the modified XML to a file in Unicode format. doc.PreserveWhitespace = True Dim wrtr As XmlTextWriter = New XmlTextWriter("C:\Q317665_Out.xml", Encoding.Unicode) doc.WriteTo(wrtr) wrtr.Close() Console.WriteLine("C:\Q317665_Out.xml is created") Console.ReadLine() Catch xmlex As XmlException ' Handle the Xml Exceptions here. Console.WriteLine("{0}", xmlex.Message) Catch ex As Exception ' Handle the generic Exceptions here. Console.WriteLine("{0}", ex.Message) End Try End Sub End Module
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.
- 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:
<?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>
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:
Keywords: kbhowtomaster kbbcl KB317665