MSDN

Microsoft Docs

XmlElement Class

Represents an element in an XML document. This class provides methods and properties to manipulate element nodes, attributes, and child nodes.

Overview
Syntax
Members
Examples
Remarks

Namespace

System.Xml

Assembly

System.Xml.dll

Inheritance

Object → XmlNode → XmlElement

public sealed class XmlElement : XmlNode

Constructors

  • XmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc)

Properties

MemberTypeDescription
AttributesXmlAttributeCollectionGets the collection of attributes for this element.
InnerTextstringGets or sets the concatenated values of the node and all its child nodes.
OuterXmlstringGets the markup representing this node and all its child nodes.
TagNamestringGets the name of the element.

Methods

MemberSignatureDescription
GetAttributestring GetAttribute(string name)Returns the value of the attribute with the specified name.
SetAttributevoid SetAttribute(string name, string value)Creates or changes an attribute with the specified name and value.
RemoveAttributevoid RemoveAttribute(string name)Removes the attribute with the specified name.
AppendChildXmlNode AppendChild(XmlNode newChild)Adds the specified node to the end of the list of child nodes.

Example: Creating an XML Document

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();

        // Create the root element
        XmlElement root = doc.CreateElement("books");
        doc.AppendChild(root);

        // Add a child element
        XmlElement book = doc.CreateElement("book");
        book.SetAttribute("id", "b1");
        root.AppendChild(book);

        // Add nested elements
        XmlElement title = doc.CreateElement("title");
        title.InnerText = "Programming C#";
        book.AppendChild(title);

        XmlElement author = doc.CreateElement("author");
        author.InnerText = "John Doe";
        book.AppendChild(author);

        Console.WriteLine(doc.OuterXml);
    }
}

Output:

<books>
  <book id="b1">
    <title>Programming C#</title>
    <author>John Doe</author>
  </book>
</books>

The XmlElement class provides full support for XML namespaces. When creating elements, supplies a prefix and a namespace URI to ensure the element is correctly qualified.

Elements can have child elements, text nodes, comments, and processing instructions. Use the AppendChild and RemoveChild methods inherited from XmlNode to manage the hierarchy.