XML C#

Add an Element to an XML Document

This C# program demonstrates how to create an XML element and add it to an existing XML document. Notice that when we create the element below, we use the document to create the element. This is the only way to create new elements. The constructor does not work.

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' ?>" +
                "<virtues/>");

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

            // Create a new element using the document
            XmlElement qVirtueElement = qXmlDoc.CreateElement("temperance");

            // Add the new element as a child of the root
            qXmlDoc.DocumentElement.AppendChild(qVirtueElement);

            Console.WriteLine();
            Console.WriteLine("After:");
            // Serialize the XML document to display it.
            qXmlSerializer.Serialize(Console.Out, qXmlDoc);
            Console.WriteLine();
        }
    }
}
 

Output

Before:
<?xml version="1.0" encoding="IBM437"?>
<virtues />

After:
<?xml version="1.0" encoding="IBM437"?>
<virtues>
  <temperance />
</virtues>
Press any key to continue . . .
 
 

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