XML C#

Select an XML Namespace Node

This C# program demonstrates how to select an XML node from within a namespace in an existing XML document. Notice that we need to pass in an XML namespace manager which contains the correct namespace.

Program.cs

using System;
using System.Xml;
using System.Xml.Serialization;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            // Create the XmlDocument.
            XmlDocument qXmlDoc = new XmlDocument();
            qXmlDoc.LoadXml("<?xml version='1.0' ?>" +
                @"<lessons xmlns:xoax=""http://xoax.net/"">" +
                "<lesson1>Simple Sets</lesson1>" +
                "<xoax:lesson2>Number Systems</xoax:lesson2>" +
                "</lessons>");

            // Serialize the XML document to display it.
            XmlSerializer qXmlSerializerDoc = new XmlSerializer(typeof(XmlDocument));
            qXmlSerializerDoc.Serialize(Console.Out, qXmlDoc);
            Console.WriteLine();

            XmlNamespaceManager qNamespaceManager = new XmlNamespaceManager(qXmlDoc.NameTable);
            qNamespaceManager.AddNamespace("xoax", "http://xoax.net/");

            // Select the node with the namespace manager.
            XmlNode qNode = qXmlDoc.SelectSingleNode("lessons/xoax:lesson2", qNamespaceManager);
            Console.WriteLine();
            Console.WriteLine("The selected node:");
            // Serialize the XML node to display it.
            XmlSerializer qXmlSerializerNode = new XmlSerializer(typeof(XmlNode));
            qXmlSerializerNode.Serialize(Console.Out, qNode);
            Console.WriteLine();
        }
    }
}
 

Output

<?xml version="1.0" encoding="IBM437"?>
<lessons xmlns:xoax="http://xoax.net/">
  <lesson1>Simple Sets</lesson1>
  <xoax:lesson2>Number Systems</xoax:lesson2>
</lessons>

The selected node:
<?xml version="1.0" encoding="IBM437"?>
<xoax:lesson2 xmlns:xoax="http://xoax.net/">Number Systems</xoax:lesson2>
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.