Working with XML

How to:

using System;
using System.Xml;
using System.Xml.Linq;

class Program
     static void Main()
        var xmlString = @"<bookstore>
                              <title lang=""en"">Head First C#</title>

        // Parse the string into an XDocument
        XDocument doc = XDocument.Parse(xmlString);

        // Add a new book
            new XElement("book",
                new XElement("title", "Learning XML", new XAttribute("lang", "en")),
                new XElement("price", 29.99)

        // Write the XML to console

        // Load the document
        XmlDocument xmlDoc = new XmlDocument();

        // Retrieve all prices
        XmlNodeList prices = xmlDoc.GetElementsByTagName("price");
        foreach (XmlNode price in prices)

// Sample Output:
// <bookstore>
//  <book>
//    <title lang="en">Head First C#</title>
//    <price>39.99</price>
//  </book>
//  <book>
//    <title lang="en">Learning XML</title>
//    <price>29.99</price>
//  </book>
// </bookstore>
// 39.99
// 29.99

Deep Dive

XML’s been around since the late ’90s, making it a grandpa in tech years. It was conjured up for data portability and ease of human reading. Alternatives like JSON are now nipping at its heels, especially in web contexts, because it’s lighter and, for many, simpler to handle. But XML still holds its ground in numerous legacy systems and certain communications protocols. With XML, you get a schema to validate your structure and namespaces to avoid tag clashes—features that speak of its enterprise-ready maturity.

In C#, System.Xml.Linq and System.Xml namespaces are two big guns to work with XML. LINQ to XML (XDocument, XElement) is more modern and more elegant—you’ve seen its magic in the example. XmlDocument gives you the DOM (Document Object Model) approach—a bit old school, but some folks swear by its power.

See Also