SoFunction
Updated on 2025-03-07

C# Operate XML documents using XmlDocument class method

W3C formulates XML DOM standards. Many programming languages ​​provide APIs that support the W3C XML DOM standard. I have introduced how to load and query XML documents using Javascript in my previous article. In this article, I will introduce the XmlDocument class in .Net. It supports and extends the W3C XML DOM standard. It loads the entire XML document into memory first, and then operates on the XML document. Therefore, if the XML document content is too large, it is not recommended to use the XmlDocument class because it will consume too much memory. For large XML documents, you can use the XmlReader class to read. Because XmlReader uses Steam to read files, it will not consume too much memory. Let’s take a look at how to use the XmlDocument class.
(I) Loading
There are three common methods to load XML:
public virtual void Load(string filename);
public virtual void Load(Stream inStream);
public virtual void LoadXml(string xml);
The following code demonstrates how to use them:
Copy the codeThe code is as follows:

XmlDocument xmlDoc = new XmlDocument();
("");
Entity retrievedAnnotation = _orgService.Retrieve("annotation"
, new Guid("C1B13C7F-F430-E211-8FA1-984BE1731399"), new ColumnSet(true));
byte[] fileContent = Convert.FromBase64String(retrievedAnnotation["documentbody"].ToString());
MemoryStream ms = new MemoryStream(fileContent);
XmlDocument xmlDoc2 = new XmlDocument();
(ms);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
XmlDocument xmlDoc3 = new XmlDocument();
(str);

(II) Query
XPath can be used for querying XML elements, attributes, and text. For specific definitions, please refer to w3school.
First, you should understand the XPath expression:
expression describe
nodename Select all children of this node.
/ Select from the root node.
// Select nodes in the document from the current node selected by the match, regardless of their location.
. Select the current node.
.. Select the parent node of the current node.
@ Select attributes.

We mainly use two methods to query XML documents, SelectNodes(xpath expression) and SelectSingleNode(xpath expression).
SelectNodes returns an XmlNodeList object, that is, all xml nodes that meet the xpath expression will be returned, and you need to traverse the returned result.
SelectSingleNode returns only the first node that conforms to the xpath expression, or returns null.
As an example, we will give some demonstrations:
Copy the codeThe code is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer city="Beijing" country="China" name="Lenovo">
<Contact gender="female" title="Support">Li Li</Contact>
</Customer>
<Customer city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
</Customer>
</Customers>

1. Return all Contact nodes:
XmlNodeList nodelist = ("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
();
}
The output result is:
<Contact gender="female" title="Support">Li Li</Contact>
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
2. Return customer with id 02:
XmlNode node = ("/Customers/Customer[@id='02']");
();
The output result is:
<Customer city="Amsterdam" country="The Netherlands" name="Shell">
<Contact gender="male" title="Sales Person">Aaron Babbitt</Contact>
<Contact gender="female" title="Sales Manager">Daisy Cabell</Contact>
<Contact gender="male" title="Sales Person">Gabriel Eads</Contact>
</Customer>
3. Return a contact with the contact name Li Li:
XmlNode node = ("/Customers/Customer/Contact[text()='Li Li']");
();
Output result:
<Contact gender="female" title="Support">Li Li</Contact>
4. Returns a customer with contact named Li Li. Note the difference between 3:
XmlNode node = ("/Customers/Customer[Contact/text()='Li Li']");
();
Output result:
<Customer city="Beijing" country="China" name="Lenovo">
<Contact gender="female" title="Support">Li Li</Contact>
</Customer>
5. (1) Get outer xml:
XmlNode node = ("/Customers/Customer[@id='02']");
();
(2) Get inner xml:
XmlNode node = ("/Customers/Customer[@id='02']");
();
(3) Get text
XmlNode node = ("/Customers/Customer/Contact[text()='Li Li']");
();
(4) Get attributes
XmlNode node = ("/Customers/Customer/Contact[text()='Li Li']");
(["gender"].Value);
(III) Create
Take creating the following XML document as an example:
Copy the codeThe code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<Customer name="Lenovo" country="China" city="Beijing">
<Contact title="Support" gender="female">Li Li</Contact>
</Customer>
</Customers>

Copy the codeThe code is as follows:

var xmlDoc = new XmlDocument();
//Create the xml declaration first
(("1.0", "utf-8", null));
//Create the root node and append into doc
var el = ("Customers");
(el);
// Customer Lenovo
XmlElement elementCustomer = ("Customer");
XmlAttribute attrID = ("id");
= "01";
(attrID);
XmlAttribute cityID = ("city");
= "Beijing";
(cityID);
XmlAttribute attrCountry = ("country");
= "China";
(attrCountry);
XmlAttribute nameCountry = ("name");
= "Lenovo";
(nameCountry);
(elementCustomer);
// Contact Li Li
XmlElement elementContact = ("Contact");
= "Li Li";
XmlAttribute attrGender = ("gender");
= "female";
(attrGender);
XmlAttribute titleGender = ("title");
= "Support";
(titleGender);
(elementContact);
("");

Summarize:The XmlDocument class is a class provided in the .Net API that supports the W3C XML DOM standard. It can be used to create and query XML documents. Since XmlDocument needs to load all the contents of the XML document into memory, it is not suitable for XML documents with too large readings, but can use XmlReader to complete the reading.