XML C#

Add an Attribute to an XML Element

This C# program demonstrates how to create an XML attribute and add it to an existing XML element. Notice that when we create the attribute below, we use the document to create the attribute. This is the only way to create new attributes. 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>" +
                "</virtues>");
            Console.WriteLine("Before adding attribute");
            // Serialize the XML document to display it.
            XmlSerializer qXmlSerializer = new XmlSerializer(typeof(XmlDocument));
            qXmlSerializer.Serialize(Console.Out, qXmlDoc);
            Console.WriteLine();

            // Create and Add an attribute
            XmlAttribute qCodeAttribute = qXmlDoc.CreateAttribute("type");
            qCodeAttribute.Value = "theological";
            qXmlDoc.DocumentElement.Attributes.Append(qCodeAttribute);

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

Output

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

After adding attribute
<?xml version="1.0" encoding="IBM437"?>
<virtues type="theological">
</virtues>
Press any key to continue . . .
 
 

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