XML C#

Add an Element with an Attribute

This C# program demonstrates how to create an XML element and add an attribute and a child node to it and add it to an existing XML document. Notice that when we create the elements and attribute below, we use the document to create them. This is the only way to do it. The constructors do 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>" +
                "<virtue type='theological'><name>Faith</name></virtue>" +
                "<virtue type='lively'><name>Chastity</name></virtue>" +
                "</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
            XmlElement qVirtueElement = qXmlDoc.CreateElement("virtue");
            // Adding an attribute
            XmlAttribute qCodeAttribute = qXmlDoc.CreateAttribute("type");
            qCodeAttribute.Value = "theological";
            qVirtueElement.Attributes.Append(qCodeAttribute);
            // Adding a child element
            XmlElement qNameElement = qXmlDoc.CreateElement("name");
            qNameElement.InnerText = "Hope";
            qVirtueElement.AppendChild(qNameElement);

            // Select to the virtues element because we will insert this one into it
            XmlNode qVirtuesNode = qXmlDoc.SelectSingleNode("virtues");
            qVirtuesNode.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>
  <virtue type="theological">
    <name>Faith</name>
  </virtue>
  <virtue type="lively">
    <name>Chastity</name>
  </virtue>
</virtues>

After:
<?xml version="1.0" encoding="IBM437"?>
<virtues>
  <virtue type="theological">
    <name>Faith</name>
  </virtue>
  <virtue type="lively">
    <name>Chastity</name>
  </virtue>
  <virtue type="theological">
    <name>Hope</name>
  </virtue>
</virtues>
Press any key to continue . . .
 
 

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