15.1. Reading and Accessing XML Data in Document Order

Problem

You need to read in all the elements of an XML document and obtain information about each element, such as its name and attributes.

Solution

Create an XmlReader and use its Read method to process the document as shown in Example 15-1.

Example 15-1. Reading an XML document

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

namespace CSharpRecipes
{

    public class AccessXml
    {
        public static void AccessXml( )
        {
            // New LINQ to XML syntax for constructing XML
            XDocument xDoc = new XDocument(
                                new XDeclaration("1.0", "UTF-8", "yes"),
                                new XComment("My sample XML"),
                                new XProcessingInstruction("myProcessingInstruction",
                                    "value"),
                                new XElement("Root",
                                    new XElement("Node1",
                                        new XAttribute("nodeId", "1"), "FirstNode"),
                                    new XElement("Node2",
                                        new XAttribute("nodeId", "2"), "SecondNode"),
                                    new XElement("Node3",
                                        new XAttribute("nodeId", "1"), "ThirdNode")
                                )
                              );

            // write out the XML to the console
            Console.WriteLine(xDoc.ToString( ));

            // create an XmlReader from the XDocument
            XmlReader reader = xDoc.CreateReader( );
            reader.Settings.CheckCharacters = true;
            int level = 0;
            while (reader.Read( ))
            {
                switch (reader.NodeType)
                {

                    case XmlNodeType.CDATA:
                        Display(level, "CDATA: {0}", reader.Value);
                        break;
                    case XmlNodeType.Comment:
                        Display(level, "COMMENT: {0}", reader.Value);
                        break;
                    case XmlNodeType.DocumentType:
                        Display(level, "DOCTYPE: {0}={1}",
                                reader.Name, reader.Value);
                        break;


                    case XmlNodeType.Element:
                        Display(level, "ELEMENT: {0}", reader.Name); level++; ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.