XmlElement Class

Namespace: System.Xml
Assembly: System.Xml.dll

Represents an element node in the XML document object model (DOM).

Syntax

public class XmlElement : XmlLinkedNode

Remarks

An XmlElement is a node that represents an XML element. It can contain other nodes, such as child elements, text, comments, and processing instructions. XmlElement implements the IXmlNode interface.

You can create an XmlElement using the CreateElement method of the XmlDocument class.

Properties

Methods

Example

Creating and Manipulating an XmlElement


using System;
using System.Xml;

public class XmlElementExample
{
    public static void Main(string[] args)
    {
        // Create an XmlDocument
        XmlDocument doc = new XmlDocument();

        // Create an XmlElement
        XmlElement rootElement = doc.CreateElement("bookstore");
        doc.AppendChild(rootElement);

        // Create another XmlElement
        XmlElement bookElement = doc.CreateElement("book");
        rootElement.AppendChild(bookElement);

        // Set an attribute
        bookElement.SetAttribute("category", "programming");

        // Create child elements
        XmlElement titleElement = doc.CreateElement("title");
        titleElement.InnerText = ".NET Programming";
        bookElement.AppendChild(titleElement);

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

        // Get an attribute
        string category = bookElement.GetAttribute("category");
        Console.WriteLine($"Book category: {category}"); // Output: Book category: programming

        // Get child elements by tag name
        XmlNodeList titleNodes = bookElement.GetElementsByTagName("title");
        if (titleNodes.Count > 0)
        {
            Console.WriteLine($"Book title: {titleNodes[0].InnerText}"); // Output: Book title: .NET Programming
        }

        // Output the XML
        Console.WriteLine("\nXML Structure:");
        Console.WriteLine(doc.OuterXml);
    }
}