Microsoft Docs

On this page

System.Xml.XmlNode Class

The XmlNode class is the abstract base class for all nodes in an XML Document Object Model (DOM). It provides core properties and methods for navigating, creating, and manipulating XML document structures.

Inheritance

Object
   ↳ XmlNode

Properties

NameTypeDescription
NameStringGets the name of the current node.
ValueStringGets or sets the value of the node.
ParentNodeXmlNodeThe parent of this node (null for the document node).
ChildNodesXmlNodeListA collection of the child nodes of this node.
AttributesXmlAttributeCollectionGets the attribute collection if this node is an element.
InnerXmlStringGets or sets the markup representing the child nodes of this node.
OuterXmlStringGets the markup representing this node and its children.

Methods

NameSignatureDescription
AppendChildXmlNode AppendChild(XmlNode newChild)Adds the specified node to the end of the child node list.
RemoveChildXmlNode RemoveChild(XmlNode oldChild)Removes the specified child node from the child node list.
SelectNodesXmlNodeList SelectNodes(string xpath)Returns a list of nodes matching the XPath expression.
SelectSingleNodeXmlNode SelectSingleNode(string xpath)Returns the first node that matches the XPath expression.
CloneNodeXmlNode CloneNode(bool deep)Creates a duplicate of the node. If deep is true, also clones descendants.
WriteContentTovoid WriteContentTo(XmlWriter w)Writes the child nodes of this node to the specified XmlWriter.

Examples

The following example creates an XML document, adds elements, and retrieves values using XmlNode methods.

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("books");
        doc.AppendChild(root);

        XmlElement book = doc.CreateElement("book");
        book.SetAttribute("id", "b1");
        root.AppendChild(book);

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

        Console.WriteLine(doc.OuterXml);

        // Select the title node using XPath
        XmlNode titleNode = doc.SelectSingleNode("//book/title");
        Console.WriteLine($\"Title: {titleNode.InnerText}\");
    }
}