C # how to operate XML documents using the XmlDocument class

Source: Internet
Author: User

W3C has developed xml dom standards. Many programming languages provide APIs that support W3C xml dom standards. In my previous article, I introduced how to use Javascript to load and query XML documents. 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 the memory and then performs operations on the XML document. Therefore, if the content of the XML document is too large, the XmlDocument class is not recommended because it consumes too much memory. You can use the XmlReader class to read large XML documents. Because XmlReader uses Steam to read files, it does not consume much memory. The following describes how to use the XmlDocument class.
(1) 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 codeThe Code is as follows: 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
You can use XPath to query XML elements, attributes, and texts. For specific definitions, see w3school.
First, you should understand the XPath expression:

Expression Description
Nodename Select all child nodes of the node.
/ Select from the root node.
// Select the nodes in the document from the current node that matches the selected node, 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 comply with the xpath expression will be returned. You need to traverse the returned results.
SelectSingleNode returns only the first node that complies with the xpath expression or null.
The following XML file is used as an example for Demonstration:Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Customers>
<Customer id = "01" city = "Beijing" country = "China" name = "Lenovo">
<Contact gender = "female" title = "Support"> 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 ("/Mers MERs/Customer/Contact ");
Foreach (XmlNode node in nodelist)
{
Console. WriteLine (node. OuterXml );
}
Output result:
<Contact gender = "female" title = "Support"> 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 the customer with id 02:
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer [@ id = '02']");
Console. WriteLine (node. OuterXml );
Output result:
<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. The returned contact contains the contact name Li:
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer/Contact [text () = 'lili']");
Console. WriteLine (node. OuterXml );
Output result:
<Contact gender = "female" title = "Support"> Li </Contact>
4. Return the customer with the contact name Li. Note:
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer [Contact/text () = 'lili']");
Console. WriteLine (node. OuterXml );
Output result:
<Customer id = "01" city = "Beijing" country = "China" name = "Lenovo">
<Contact gender = "female" title = "Support"> Li </Contact>
</Customer>
5. (1) Get outer xml:
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer [@ id = '02']");
Console. WriteLine (node. OuterXml );
(2) Get inner xml:
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer [@ id = '02']");
Console. WriteLine (node. InnerXml );
(3) Get text
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer/Contact [text () = 'lili']");
Console. WriteLine (node. InnerText );
(4) Get attributes
XmlNode node = xmlDoc. SelectSingleNode ("/Mers MERs/Customer/Contact [text () = 'lili']");
Console. WriteLine (node. Attributes ["gender"]. Value );
(3) create
Take the following XML document as an example:Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Customers>
<Customer id = "01" name = "Lenovo" country = "China" city = "Beijing">
<Contact title = "Support" gender = "female"> Li </Contact>
</Customer>
</Customers>

Copy codeThe Code is as follows: 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 ("MERs ");
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
XmlElement elementContact = xmlDoc. CreateElement ("Contact ");
ElementContact. InnerText = "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:The XmlDocument class is a class provided by the. Net API that supports the W3C xml dom standard. You can use it to create and query XML documents. Because XmlDocument needs to load all the content of XML documents into the memory, it is not suitable to use the XmlDocument class for reading XML documents with too much content, but XmlReader can be used for reading.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.