Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

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
View Source
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Xml\ModifyXmlDocument\]

The following code uses an XPath expression to identify an XML node. The node is then deleted.

string xpath = "/bookstore/book[title='The Gorgias']";
XmlNode node = doc.SelectSingleNode(xpath);

The following code shows how you can use the methods and properties on the XmlNode class to build a new sub-tree of nodes.

XmlNode bookstore = doc.DocumentElement;

XmlElement book = doc.CreateElement("book");
book.SetAttribute("genre", "novel");
book.SetAttribute("publicationdate", "1998");
book.SetAttribute("ISBN", "0-553-21311-03");

XmlElement title = doc.CreateElement("title"); 
title.InnerText  = "Moby Dick";

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.

foreach (XmlNode node in doc.SelectNodes("//price"))
node.InnerText = (XmlConvert.ToDouble(node.InnerText) * 1.2) + "";



  1. The XmlDocument, XmlNode and other classes implement the W3C Document Object Model Level 1 Core and the Core DOM Level 2 specifications.
  2. The XmlDocument is an in-memory (cache) tree representation of an XML document.
  3. 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 � 2004 Microsoft Corporation. All rights reserved.