Select Root : XmlDocument « XML « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

public class MainClass
{

    public static void Main()
    {
        XmlDocument mDocument = new XmlDocument();
        XmlNode mCurrentNode;

        mDocument.Load("XPathQuery.xml");
        mCurrentNode = mDocument.DocumentElement.SelectSingleNode("//books");

        RecurseXmlDocument(mCurrentNode);

    }

    private void DisplayList(XmlNodeList nodeList)
    {
        foreach (XmlNode node in nodeList)
        {
            RecurseXmlDocumentNoSiblings(node);
        }
    }

    static void RecurseXmlDocumentNoSiblings(XmlNode root)
    {
        if (root is XmlElement)
        {
            Console.WriteLine(root.Name);
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild);
        }
        else if (root is XmlText)
        {
            string text = ((XmlText)root).Value;
            Console.WriteLine(text);
        }
        else if (root is XmlComment)
        {
            string text = root.Value;
            Console.WriteLine(text);
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild);
        }
    }
    static void RecurseXmlDocument(XmlNode root)
    {
        if (root is XmlElement)
        {
            Console.WriteLine(root.Name);
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild);
            if (root.NextSibling != null)
                RecurseXmlDocument(root.NextSibling);
        }
        else if (root is XmlText)
        {
            string text = ((XmlText)root).Value;
            Console.WriteLine(text);
        }
        else if (root is XmlComment)
        {
            string text = root.Value;
            Console.WriteLine(text);
            if (root.HasChildNodes)
                RecurseXmlDocument(root.FirstChild);
            if (root.NextSibling != null)
                RecurseXmlDocument(root.NextSibling);
        }
    }
}








30.8.XmlDocument
30.8.1.XmlDocument Event: node changed, node inserted and node removed
30.8.2.Add attribute to Xml document
30.8.3.Read Write Xml
30.8.4.Remove child from XmlDocument
30.8.5.Get child count
30.8.6.Get element by tag name
30.8.7.Get value from selected node
30.8.8.Loop Through XmlDocument Recursively
30.8.9.Select Root
30.8.10.Three ways to load Xml to XmlDocument
30.8.11.Fast select by ID using DOM API
30.8.12.Create Node and append to XmlDocument
30.8.13.Select nodes from xml document