How Do I...Modify XML with the XmlDocument Class?
This sample illustrates how to modify an XML document using classes based on the W3C Document Object Model (DOM). The DOM is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of the document. This sample loads an XmlDocument object, modifies the XML data and saves the changes to an XML file.
VB ModifyXmlDocument.exe
The following code uses an XPath expression to identify an XML node. The node is then deleted.
Dim xpath As String = "/bookstore/book[title='The Gorgias']"
Dim node As XmlNode = doc.SelectSingleNode(xpath)
node.ParentNode.RemoveChild(node)
VB
The following code shows how you can use the methods and properties on the XmlNode class to build a new sub-tree of nodes.
Dim bookstore As XmlNode = doc.DocumentElement
Dim book As XmlElement = doc.CreateElement("book")
book.SetAttribute("genre", "novel")
book.SetAttribute("publicationdate", "1998")
book.SetAttribute("ISBN", "0-553-21311-03")
Dim title As XmlElement = doc.CreateElement("title")
title.InnerText = "Moby Dick"
book.AppendChild(title)
...
bookstore.AppendChild(book)
VB
The following code increases the price for each book. The code shows how to use the XmlConvert.ToDouble method to convert the text value of the price element to Double and calculate the new book price.
Dim node As XmlNode
For Each node In doc.SelectNodes("//price")
node.InnerText = XmlConvert.ToDouble(node.InnerText) * 1.2.ToString()
Next node
VB
Summary
- The XmlDocument, XmlNode and other classes implement the W3C Document Object Model Level 1 Core and the Core DOM Level 2 specifications.
- The XmlDocument is an in-memory (cache) tree representation of an XML document.
- There are different node types specializing from XmlNode to enable you to manipulate the XML document.
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|