C operations XML documents use XmlDocument class methods

  • 2020-05-07 20:21:40
  • OfStack

W3C established 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 introduce the XmlDocument class in.Net. It supports and extends the W3C XML DOM standard. It loads the entire XML document into memory before operating 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. Now let's see how to use the XmlDocument class.
(1) loads
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) queries
Queries on XML's elements, attributes, and text can use XPath. See w3school for a specific definition.
First of all, you should understand 1 XPath expression:
expression describe nodename Select all children 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. .. Selects 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 iterate over 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, let's do some demonstration:
 
<?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 to 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 as 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 >
Return customer with contact name 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) obtain 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 attributes
XmlNode node = xmlDoc.SelectSingleNode("/Customers/Customer/Contact[text()='Li Li']");
Console.WriteLine(node.Attributes["gender"].Value);
(3) creates
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"); 

summary: XmlDocument class is a class provided in Net API to support W C XML DOM standard. You can use it to create and query XML documents. Since XmlDocument loads all the contents of XML documents into memory, the XmlDocument class is not suitable for XML documents that read too much. Instead, XmlReader can be used for reading.

Related articles: