This C# program demonstrates how to add an XML element to an existing namespace in 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.
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 virtues node so that we can insert the new element 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); // Add a new element in the namespace XmlElement qNewElement = qXmlDoc.CreateElement("xoax", "lesson2", "http://xoax.net/"); qNewElement.InnerText = "Number Systems"; qLessonsNode.AppendChild(qNewElement); // Serialize the XML document to display it. XmlSerializer qXmlSerializer = new XmlSerializer(typeof(XmlDocument)); qXmlSerializer.Serialize(Console.Out, qXmlDoc); Console.WriteLine(); } } }
<?xml version="1.0" encoding="IBM437"?> <lessons xmlns:xoax="http://xoax.net/"> <lesson1>Simple Sets</lesson1> <xoax:lesson2>Number Systems</xoax:lesson2> </lessons> Press any key to continue . . .
© 20072025 XoaX.net LLC. All rights reserved.