XML C#

Add a Namespace to an XML Document

This C# program demonstrates how to add an XML namespace to an existing XML document. We selected the root node of the document as the element to which to add the namespace. Note that it does matter where the namespace is added. So, be sure to scope the namespace correctly.

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>" +
                "<lesson1>Simple Sets</lesson1>" +
                "</lessons>");

            // Select the lessons node so that we can insert the namespace into it.
            XmlNode qLessonsNode = qXmlDoc.SelectSingleNode("lessons");

            // Add the xoax namespace
            XmlAttribute qXoaxNamespaceAttr = qXmlDoc.CreateAttribute("xmlns:xoax");
            qXoaxNamespaceAttr.Value = @"http://xoax.net/";
            qLessonsNode.Attributes.Append(qXoaxNamespaceAttr);

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

Output

<?xml version="1.0" encoding="IBM437"?>
<lessons xmlns:xoax="http://xoax.net/">
  <lesson1>Simple Sets</lesson1>
</lessons>
Press any key to continue . . .
 
 

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