SoFunction
Updated on 2025-03-07

Detailed explanation of using XmlDocument to operate XML under C#

1. XML DOM Overview

XML documents are case sensitive, attributes are enclosed in quotes, and each tag must be closed.

DOM is a tree-like representation of an XML document in memory.

Inheritance relationship diagram:

XmlNode;//XML node......XmlDocument;//XML Documentation............XmlDataDocument;//Document related to Dataset......XmlDocumentFragment;// Document snippet......XmlLinkedNode;//Connect nodes (abstract class)............XmlDeclaration;//XML statement:............XmlDocumentType;//Document Type............XmlElement;//element............XmlEntityReference;//Entity reference node............XmlProcessingInstruction;//Processing instructions............XmlCharacterData;//Character data (abstract class)..................XmlCDataSection;//CDATA Festival..................XmlComment;//Note..................XmlSignificantWhitespace;//Effective blank..................XmlWhitespace;//blank..................XmlText;//Text content of element or attribute......XmlAttribute;//property......XmlEntity;//Entity Statement......XmlNotation;//Notation Statement

2. XML members

1. XMl node: XmlNode

1. Attributes:

  • Child​Nodes: All child nodes.
  • First​Child: The first child.
  • Has​Child​Nodes: Get whether there are any child nodes.
  • Last​Child: The last child node.
  • Parent​Node: Parent node (for nodes that can have parent).
  • Next​Sibling: A sibling node immediately after this node.
  • Previous​Sibling: A sibling node immediately before this node.
  • Inner​Text: Text values ​​of a node and all its child nodes.
  • Inner​Xml: XML tags for child nodes.
  • Outer​Xml: This node and all its child nodes XML tags.
    • Node​Type: Get the type of the current node.
    • Value: The value of the node.
    • Attributes: The node's properties XmlAttributeCollection.
    • Owner​Document: The XmlDocument to which the node belongs.

    2. Method:

    • Append​Child(Xml​Node): Added to the end of the child node list of this node.
    • Prepend​Child(Xml​Node): Append to the beginning of the child node list of this node.
    • Insert​After(Xml​Node, Xml​Node): Insert the specified node immediately after the specified node.
    • Insert​Before(Xml​Node, Xml​Node): Insert the specified node immediately before inserting the specified node.
      • Remove​All() : Removes all child nodes and/or properties of the current node.
      • Remove​Child(Xml​Node): Removes the specified child node.
      • Replace​Child(Xml​Node, Xml​Node): Replace child node newChild with the oldChild node.
      • Select​Nodes(String): Select a list of nodes matching the XPath expression.
      • Select​Single​Node(String): Select the first XmlNode that matches the XPath expression.
      • Write​Content​To(Xml​Writer): When rewritten in a derived class, all children of the node are saved to the specified XmlWriter.
      • Write​To(Xml​Writer): When rewritten in the derived class, save the current node to the specified XmlWriter.
      • Clone() : Create a copy of this node.
      • Clone​Node(Boolean): Creates a copy of the node when rewritten in the derived class
      • Create​Navigator() : Create XPathNavigator to browse this object.

      2. XML document: XMLDocument

      1. Attributes:

      • Document​Element: Get the root of the document XmlElement.
      • Document​Type: Get the node containing the DOCTYPE declaration.
      • Preserve​Whitespace : Gets or sets a value indicating whether to keep a blank area in the element content.
      • Schemas : Gets or sets the XmlSchemaSet object associated with this XmlDocument.
      • Xml​Resolver: Set up XmlResolver for parsing external resources.

      2. Method:

      • Get​Element​ById(String): Gets the XmlElement with the specified ID.
      • Get​Elements​ByTag​Name(String): Returns an XmlNodeList that contains a list of all child elements that match the specified Name.
      • Import​Node(Xml​Node, Boolean): Imports a node from another document to the current document. Load(Stream) Loads the XML document from the specified stream.
      • Load(String): Load the XML document from the specified URL. .
      • Load​Xml(String): Load the XML document from the specified string.
      • Save(String): Save the XML document to the specified file. If the specified file exists, this method overwrites it.
      • Validate(Validation​Event​Handler): Verify that XmlDocument is the XML Schema Definition Language (XSD) schema contained in the Schemas property.
      • Read​Node(Xml​Reader): Create an XmlNode object based on the information in XmlReader. The reader must be positioned on a node or property.
      • Create​****(String): Creates Xml*** with the specified Name.
        • Create​Navigator() : Creates a new XPathNavigator object to navigate this document.

        3. Events:

        • Node​Changing、Node​Changed:Occurs when the value of the node belonging to the document will be changed.
        • Node​Inserting、Node​Inserted:Occurs when a node belonging to the document is inserted into another node.
        • Node​Removing、Node​Removed:Occurs when a node belonging to the document has been removed from its parent.

        3. XML element: XmlElement

        1. Attributes:

        • Has​Attributes: Gets a boolean value indicating whether the current node has any attributes.
        • Is​Empty: Get or set the marking format of the element.
        • Schema​Info: Get the post-schema verification information set assigned to this node as the result of schema verification.

        2. Method:

        • Get​Attribute(String): Returns the value of the attribute with the specified name.
        • Get​Attribute​Node(String): Returns XmlAttribute with the specified name.
        • Has​Attribute(String): Determines whether the current node has a characteristic with the specified name.
        • Get​Elements​ByTag​Name(String): Returns an XmlNodeList that contains a list of all child elements that match the specified Name.
        • Remove​All​Attributes() : Removes all specified properties from the element. The default feature is not removed.
        • Remove​Attribute(String): Removes attributes by name.
        • Remove​Attribute​At(Int32): Removes the attribute node with the specified index from the element. (If the removed feature has a default value, it will be replaced immediately).
        • Remove​Attribute​Node(String, String): Removes the XmlAttribute specified by the local name and namespace URI. (If the removed feature has a default value, it will be replaced immediately)

        3. Create and query XML

        Namespaces to be added:

        using ;

        1. Create XmlDocument

        XmlDocument xmldoc = new XmlDocument();
        //Add to XML declaration paragraph,XmlDeclaration xmldecl;
        xmldecl = 
          
        ("1.0", "gb2312", null);
        (xmldecl);
        
        //Add a root elementXmlElement xmlelem = 
          
        ("", "Employees", "");
        (xmlelem);
        //Add another elementfor (int i = 1; i < 3; i++)
        {
            XmlNode root = ("Employees");//Find    XmlElement xe1 = ("Node");//Create a node    ("genre", "Li Zanhong");//Set the genre attribute of this node    ("ISBN", "2-3631-4");//Set the ISBN attribute of this node
            XmlElement xesub1 = ("title");
             = "CS from Beginner to Mastery";//Set text node
            (xesub1);//Add to node
            XmlElement xesub2 = ("author");
             = "Hou Jie";
            (xesub2);
            XmlElement xesub3 = ("price");
             = "58.3";
            (xesub3);
        
            (xe1);//Add to node
        }
        //Save the created XML document("../../");

        Result: A file named is generated, with the following contents,

        <xml version="1.0" encoding="gb2312"?>
        <Employees>
          <Node genre="Li Zanhong" ISBN="2-3631-4">
            <title>CSFrom Beginner to Mastery</title>
            <author>Hou Jie</author>
            <price>58.3</price>
          </Node>
          <Node genre="Li Zanhong" ISBN="2-3631-4">
            <title>CSFrom Beginner to Mastery</title>
            <author>Hou Jie</author>
            <price>58.3</price>
          </Node>
        </Employees>

        2. Create XmlTextWriter

        See:XmlReader and XMLWriter (abstract class)

        string strFilename = "../../";
        
        XmlTextWriter xmlWriter = new XmlTextWriter(strFilename, );//
          
        Create axmldocument
         = ;
        ();
        ("Employees");
        
        ("Node");
        ("genre", "Li Zanhong");
        ("ISBN", "2-3631-4");
        
        ("title");
        ("CS from Beginner to Mastery");
        ();
        
        ("author");
        ("Hou Jie");
        ();
        
        ("price");
        ("58.3");
        ();
        
        ();
        ();
        
        ();

        result:

        <xml version="1.0" encoding="gb2312"?>
        <Employees>
          <Node genre="Li Zanhong" ISBN="2-3631-4">
            <title>CSFrom Beginner to Mastery</title>
            <author>Hou Jie</author>
            <price>58.3</price>
          </Node>
        </Employees>

        3. Create XML fragments: ()

        XmlDocument xmldoc = new XmlDocument();
        XmlDocumentFragment docFrag = ();
         = "aa";
        ();
        XmlElement root = ; 
        (docFrag);

        4. Load the existing XML file: ()

        XmlDocument xmldoc = new XmlDocument();
        ((""));
        
        XmlElement root = ;//Get the root elementforeach (XmlNode node in )
        {
            if (["gere"].Value == "a")
            {
                foreach (XmlNode node1 in )
                {
                    if ( == "author")
                    {
                         = "aa";//Modify the text            }
                }
            }
        }

        5. Query node: SelectNodes

        string str = @"
                        
                         200
                         Authentication information matching
                          
                         ";
        
        var xd = new ();
        (str);//xml loads xml string
        XmlNamespaceManager nsManager = new XmlNamespaceManager();//Create a namespace manager
        ("xsd", "http:///2001/XMLSchema");// When adding strings, the namespace manager will atomize these strings.("xsi", "http:///2001/XMLSchema-instance");
        ("amon", "/");
        
        var rowNoteList = ("//amon:ErrorRes", nsManager);//Find nodes(rowNoteList[0]);

        return:

        <ErrorRes xmlns="/">
                  <Err_code>200</Err_code>
                  <Err_content>Authentication information matching</Err_content>
        </ErrorRes>

        6. Read xml:StreamReader according to text file

        StreamReader myFile = new StreamReader("../../", );//Notice
        string myString = ();//myString is a read string();
        
        (myString);

        4. Add a node: AppendChild

        XmlDocument xmlDoc = new XmlDocument();
        ("../../");
        XmlNode root = ("Employees");//Find
        XmlElement xe1 = ("Node");//Create a node
        ("genre", "Zhang San");//Set the genre attribute of this node("ISBN", "1-1111-1");//Set the ISBN attribute of this node
        XmlElement xesub1 = ("title");
         = "C#Beginner Help";//Set Text Node
        (xesub1);//Add to node
        XmlElement xesub2 = ("author");
         = "Master";
        (xesub2);
        
        XmlElement xesub3 = ("price");
         = "158.3";
        (xesub3);
        
        (xe1);//Add to node
        ("../../");

        Result: A node was added to the original content of the xml, with the following content,

        <xml version="1.0" encoding="gb2312"?>
        <Employees>
          <Node genre="Li Zanhong" ISBN="2-3631-4">
            <title>CSFrom Beginner to Mastery</title>
            <author>Hou Jie</author>
            <price>58.3</price>
          </Node>
          <Node genre="Li Zanhong" ISBN="2-3631-4">
            <title>CSFrom Beginner to Mastery</title>
            <author>Hou Jie</author>
            <price>58.3</price>
          </Node>
          <Node genre="Zhang San" ISBN="1-1111-1">
            &lt;title&gt;C#Beginner Help</title>    &lt;author&gt;Expert&lt;/author&gt;
            &lt;price&gt;158.3&lt;/price&gt;
          &lt;/Node&gt;
        &lt;/Employees&gt;

        5. Modify nodes

        1. Modify the value of the node (properties and subnodes):

        XmlDocument xmlDoc = new XmlDocument();
        ("../../");
        
        XmlNodeList nodeList = ("Employees").ChildNodes;//Get all child nodes of Employees node
        foreach (XmlNode xn in nodeList)//Transfer all child nodes{
            XmlElement xe = (XmlElement)xn;//Convert child node type to XmlElement type    if (("genre") == "Zhang San")//If the genre attribute value is "Zhang San"    {
                ("genre", "update Zhang San");//Then modify this property to "update Zhang San"        XmlNodeList nls = ;//Continue to get all children of xe child nodes        foreach (XmlNode xn1 in nls)//Travel        {
                    XmlElement xe2 = (XmlElement)xn1;//Convert type            if ( == "author")//If found            {
                         = "Asia Victory";//Modify            }
                }
            }
        }
        ("../../");//save。

        Result: All the original node information has been modified, the content of the xml is as follows.

        &lt;xml version="1.0" encoding="gb2312"?&gt;
        &lt;Employees&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node genre="update Zhang San" ISBN="1-1111-1"&gt;
            &lt;title&gt;C#Beginner Help</title>    &lt;author&gt;Asia Win&lt;/author&gt;
            &lt;price&gt;158.3&lt;/price&gt;
          &lt;/Node&gt;
        &lt;/Employees&gt;

        2. Modify nodes (add node properties and add node sub-nodes)

        XmlDocument xmlDoc = new XmlDocument();
        ("../../");
        
        XmlNodeList nodeList = ("Employees").ChildNodes;//Get all child nodes of Employees node
        foreach (XmlNode xn in nodeList)
        {
            XmlElement xe = (XmlElement)xn;
            ("test", "111111");//Add attributes
            XmlElement xesub = ("flag");
             = "1";
            (xesub);//Add child nodes}
        ("../../");

        Result: One property of each node is added, and one child node is also added, the content is as follows.

        &lt;xml version="1.0" encoding="gb2312"?&gt;
        &lt;Employees&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4" test="111111"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
            &lt;flag&gt;1&lt;/flag&gt;
          &lt;/Node&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4" test="111111"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
            &lt;flag&gt;1&lt;/flag&gt;
          &lt;/Node&gt;
          &lt;Node genre="update Zhang San" ISBN="1-1111-1" test="111111"&gt;
            &lt;title&gt;C#Beginner Help</title>    &lt;author&gt;Asia Win&lt;/author&gt;
            &lt;price&gt;158.3&lt;/price&gt;
            &lt;flag&gt;1&lt;/flag&gt;
          &lt;/Node&gt;
        &lt;/Employees&gt;

        6. Delete nodes

        1. Delete a certain attribute in the node:

        XmlDocument xmlDoc = new XmlDocument();
        ("../../");
        
        XmlNodeList xnl = ("Employees").ChildNodes;
        foreach (XmlNode xn in xnl)
        {
            XmlElement xe = (XmlElement)xn;
            ("genre");//Delete the genre attribute
            XmlNodeList nls = ;//Continue to get all children of xe child nodes    
            foreach (XmlNode xn1 in nls)//Travel    {
                XmlElement xe2 = (XmlElement)xn1;//Convert type
                if ( == "flag")//If found        {
                    (xe2);//Delete        }
            }
        }
        ("../../");

        Result: A property of a node and a child node of a node are deleted. The content is as follows.

        &lt;xml version="1.0" encoding="gb2312"?&gt;
        &lt;Employees&gt;
          &lt;Node ISBN="2-3631-4" test="111111"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node ISBN="2-3631-4" test="111111"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node ISBN="1-1111-1" test="111111"&gt;
            &lt;title&gt;C#Beginner Help</title>    &lt;author&gt;Asia Win&lt;/author&gt;
            &lt;price&gt;158.3&lt;/price&gt;
          &lt;/Node&gt;
        &lt;/Employees&gt;

        2. Delete nodes:

        XmlDocument xmlDoc = new XmlDocument();
        ("../../");
        
        XmlNode root = ("Employees");
        XmlNodeList xnl = ("Employees").ChildNodes;
        for (int i = 0; i &lt; ; i++)
        {
            XmlElement xe = (XmlElement)(i);
            if (("genre") == "Zhang San")
            {
                (xe);
                if (i &lt; ) i = i - 1;
            }
        }
        ("../../");

        Result: All nodes that meet the conditions were deleted, the original content:

        &lt;xml version="1.0" encoding="gb2312"?&gt;
        &lt;Employees&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node genre="Zhang San" ISBN="1-1111-1"&gt;
            &lt;title&gt;C#Beginner Help</title>    &lt;author&gt;Expert&lt;/author&gt;
            &lt;price&gt;158.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node genre="Zhang San" ISBN="1-1111-1"&gt;
            &lt;title&gt;C#Beginner Help</title>    &lt;author&gt;Expert&lt;/author&gt;
            &lt;price&gt;158.3&lt;/price&gt;
          &lt;/Node&gt;
        &lt;/Employees&gt;

        Deleted content:

        &lt;xml version="1.0" encoding="gb2312"?&gt;
        &lt;Employees&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
          &lt;Node genre="Li Zanhong" ISBN="2-3631-4"&gt;
            &lt;title&gt;CSFrom Beginner to Mastery&lt;/title&gt;
            &lt;author&gt;Hou Jie&lt;/author&gt;
            &lt;price&gt;58.3&lt;/price&gt;
          &lt;/Node&gt;
        &lt;/Employees&gt;

        3. Replace child elements

        XmlElement  elem=("title");
        ="XX";
        (elem,);

        This is all about this article about C# using XmlDocument to operate XML. I hope it will be helpful to everyone's learning and I hope everyone will support me more.