Click here to Skip to main content
13,196,566 members (54,420 online)
Click here to Skip to main content
Add your own
alternative version


56 bookmarked
Posted 14 Mar 2008

Working with XML

, 14 Mar 2008
Rate this:
Please Sign up or sign in to vote.
Reading and writing XML documents.


The eXtensible Markup Language (XML) has seen widespread adoption throughout almost every industry, in recent years. Its ability to allow applications to exchange data in a standardized format through web services and XML documents, and its adoption by SQL Server 2005 and most of Microsoft's new and upcoming applications, make the use of XML almost compulsory when creating applications in the .NET Framework. Whether you're using XML in your application's configuration file, consuming or exposing web services, working with XML in SQL Server, or working with datasets, knowing how to work with XML programmatically with the .NET Framework is an essential skill for any C# developer. This article does not cover the basics of XML itself. Instead, you will see how to work with XML using C# 2.0.

Reading and Writing XML Documents

One of the most basic tasks that you can perform with XML is manipulating the contents of an XML document. This includes traversing the list of nodes in the document, setting and querying attribute values, and manipulating the tree itself by creating and inserting new nodes. This article shows you how to read XML documents using the Document Object Model (DOM) modeled by the XmlDocument class in the System.Xml namespace. The DOM is recursive, meaning that each node has the same properties and methods as every other node in the document. The following two lists provide a brief overview of many of the properties and methods of the XmlNode class, before getting into the code sample. The XML node is the most basic unit of abstraction within a DOM-modeled document.

Commonly Used XmlNode Properties

  • Attributes - The attributes of the node (XmlAttributeCollection).
  • ChildNodes - The list of child nodes of the current node (XmlNodeList).
  • FirstChild - Returns the first child of the XML node (first being first in document order).
  • HasChildNodes - A Boolean that indicates whether the node has child nodes.
  • InnerText - Gets or sets the text inside the node.
  • InnerXml - Gets or sets the XML within the node.
  • LastChild - Returns the last child (document order relative) of the node.
  • Name - The name of the node.
  • NodeType - Indicates the type of the node. This can be several things, including (but not limited to): Document, DocumentFragment, Element, EndElement, Entity, Notation, Text, Whitespace, or XmlDeclaration.
  • OuterXml - The XML representing the current node and all its child nodes.
  • OwnerDocument - The document to which the current node belongs.
  • ParentNode - The parent node of the current node, if any.
  • PreviousSibling - Gets the node immediately preceding the current node in document order.
  • Value - Gets or sets the value of the current node.

Commonly Used XmlNode Methods

  • AppendChild - Adds a child node to the end of the current list of child nodes.
  • Clone - Creates a duplicate of the node.
  • CreateNavigator - Creates an XPathNavigator for this node.
  • InsertAfter - Inserts the given node immediately after the current node.
  • InsertBefore - Inserts the given node immediately before the current node.
  • PrependChild - Adds the given child node at the beginning of the child node list.
  • RemoveAll - Removes all child nodes.
  • RemoveChild - Removes the given child from the current node.
  • SelectNodes - Selects a list of nodes matching the XPath expression (discussed in the following section).
  • SelectSingleNode - Selects a single node that matches the XPath expression.

The XmlDocument class, which deals with the entire document, is also itself an XmlNode. If you look at the documentation for the XmlDocument class, you'll see that it inherits from XmlNode. This fits with the DOM pattern in that the document is a node that can have child nodes. The methods in the following list show some of the additional methods available to the XmlDocument that aren't part of a standard node class.

XmlDocument Class Methods

  • CreateAttribute - Creates an XmlAttribute with the given name.
  • CreateCDataSection - Creates a CData section with the given data.
  • CreateComment - Creates an XmlComment.
  • CreateDocumentFragment - Creates a document fragment.
  • CreateElement - Creates an XmlElement, an XmlNode with element-specific functionality.
  • CreateNode - Creates an XmlNode.
  • CreateTextNode - Creates an XmlText node.
  • CreateWhitespace - Creates whitespace for insertion into the document.
  • ImportNode - Imports a node from another document.
  • Load - Loads the XML from the given file.
  • LoadXml - Loads the XML from the given XML string.
  • Save - Saves the XML document.
  • Validate - Validates the XML document against a schema.

To show off the code for manipulating an XML document, we need a document. The following code shows a document called items.xml, which contains a list of items from a fictitious role-playing game and the various aspects of those items.

Using the code


<?xml version="1.0" encoding="utf-8"?>
  <item id="1" name="Flaming Sword of Doom"

"This sword will vanquish all of your foes with a single swipe">
    <attribute name="attack" value="10"/>
    <attribute name="weight" value="21" />
  <item id="2" name="Bag of Really Big Stuff"

        description="This bag can hold a lot of stuff.">
    <attribute name="weight" value="1" />
    <attribute name="capacity" value="80" />
  <item id="3" name="Broach of Bug Smashing"

        description="This broach will kill any bug. Instantly.">
    <attribute name="weight" value="1" />
    <attribute name="attack" value="11" />
      <special name="killbug" description="This thing kills any bug instantly."/>
  <item id="4" name="Wand of Traffic Vanquish"

"A single wave of this wand will part the highway before you.">
    <attribute name="weight" value="5" />
    <attribute name="attack" value="20" />
      <special name="parttraffic"

description="All nearby vehicles move out of your way." />

Although XML allows you to freely mix freeform text with markup, the examples use XML documents as pure data storage.

The following code shows the use of the XmlNode class and its associated properties and methods for traversing an XML document and displaying its contents to the console.

XML Document Display Sample

using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;

namespace ReadWriteXml
class Program
static void Main(string[] args)
    XmlDocument itemDoc = new XmlDocument();
    Console.WriteLine("DocumentElement has {0} children.",

    // iterate through top-level elements
    foreach (XmlNode itemNode in itemDoc.DocumentElement.ChildNodes)
        // because we know that the node is an element, we can do this:
        XmlElement itemElement = (XmlElement)itemNode;
        Console.WriteLine("\n[Item]: {0}\n{1}", 
        if (itemNode.ChildNodes.Count == 0)
            Console.WriteLine("(No additional Information)\n");
            foreach (XmlNode childNode in itemNode.ChildNodes)
                if (childNode.Name.ToUpper() == "ATTRIBUTE")
                    Console.WriteLine("{0} : {1}",
                else if (childNode.Name.ToUpper() == "SPECIALS")
                    foreach (XmlNode specialNode in childNode.ChildNodes)


This article has shown you how you can make use of your existing XML skills in C#. You saw how to manipulate the nodes of an XML document using the DOM class XmlDocument.

Now that you have completed this article, you should feel comfortable working with XML in any of its forms whether you're working on an ASP.NET application or a Windows Forms application.


  • March 14, 2008 - Original article.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nelson Kosta Souto
Portugal Portugal
My name is Nelson Souto, I develop software for fun and profit since 1992.

You may also be interested in...

Comments and Discussions

GeneralFluent XML Pin
BigTuna14-Mar-08 8:52
memberBigTuna14-Mar-08 8:52 
GeneralRe: Fluent XML Pin
Nelson Kosta Souto14-Mar-08 9:51
memberNelson Kosta Souto14-Mar-08 9:51 
GeneralInteresting article Pin
Jimmy Zhang14-Mar-08 7:11
memberJimmy Zhang14-Mar-08 7:11 
GeneralRe: Interesting article Pin
Nelson Kosta Souto14-Mar-08 7:41
memberNelson Kosta Souto14-Mar-08 7:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171019.1 | Last Updated 14 Mar 2008
Article Copyright 2008 by Nelson Kosta Souto
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid