C operates on XML documents using XmlDocument class methods

  • 2020-05-09 19:03:57
  • OfStack

W3C has developed the XML DOM standard. API, which supports the W3C XML DOM standard, is available in many programming languages. In a previous article, I showed you how to load and query XML documents using Javascript. In this article, I'll introduce the XmlDocument class in.Net. It supports and extends the W3C XML DOM standard. It loads the entire XML document into memory and then operates on the XML document, so if the XML document is too large, it is not recommended to use the XmlDocument class because it consumes too much memory. For large XML documents, you can use the XmlReader class to read them. Because XmlReader USES Steam (stream) to read files, it doesn't consume much memory. Let's take a look at how to use the XmlDocument class.
(1) loading
There are three common ways to load XML:
public virtual void Load(string filename);
public virtual void Load(Stream inStream);
public virtual void LoadXml(string xml);
The following code shows how to use them:
 
XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load("XMLFile1.xml"); 
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(); 
xmlDoc2.Load(ms); 
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>"; 
XmlDocument xmlDoc3 = new XmlDocument(); 
xmlDoc3.LoadXml(str); 

(2) query
Queries on XML's elements, attributes, and text can use XPath. See w3school for a specific definition.
First of all, you should know 1 about the XPath expression:
expression describe nodename Select all child nodes of this node. / Select from the root node. // Select the nodes in the document from the current node that matches the selection, regardless of their location. . Select the current node. .. Select the parent of the current node. @ Select the property.
We mainly use two methods to query XML documents, SelectNodes(xpath expression) and SelectSingleNode(xpath expression).
SelectNodes returns 1 XmlNodeList object, that is, all xml nodes that conform to the xpath expression will be returned. You need to traverse the returned results.
SelectSingleNode returns only the first node that conforms to the xpath expression, or null.
Take the following XML file as an example to demonstrate:
 
<?xml version="1.0" encoding="utf-8" ?> 
<Customers> 
<Customer id="01" city="Beijing" country="China" name="Lenovo"> 
<Contact gender="female" title="Support">Li Li</Contact> 
</Customer> 
<Customer id="02" 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 = xmlDoc.SelectNodes("/Customers/Customer/Contact");
foreach (XmlNode node in nodelist)
{
Console.WriteLine(node.OuterXml);
}
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 = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.OuterXml);
The output result is:
< Customer id="02" 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 contact containing contact named Li Li:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.OuterXml);
Output results:
< Contact gender="female" title="Support" > Li Li < /Contact >
4. Return customer containing contact named Li Li. Note the difference between and 3:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[Contact/text()='Li Li']");
Console.WriteLine(node.OuterXml);
Output results:
< Customer id="01" city="Beijing" country="China" name="Lenovo" >
< Contact gender="female" title="Support" > Li Li < /Contact >
< /Customer >
5. (1) obtain outer xml:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.OuterXml);
(2) get inner xml:
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer[@id='02']");
Console.WriteLine(node.InnerXml);
(3) to obtain text
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.InnerText);
(4) get properties
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.Attributes["gender"].Value);
(3) creation
For example, create the following XML document:
 
<?xml version="1.0" encoding="UTF-8"?> 
<Customers> 
<Customer id="01" name="Lenovo" country="China" city="Beijing"> 
<Contact title="Support" gender="female">Li Li</Contact> 
</Customer> 
</Customers> 

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

Conclusion: the XmlDocument class is a class that supports the W3C XML DOM standard provided in Net API. You can use it to create and query XML documents. Since XmlDocument loads all the contents of XML documents into memory, it is not suitable to use XmlDocument class for XML documents with too large contents. Instead, XmlReader can be used to complete the reading.

Related articles: