C # manipulating XML documents using the XmlDocument class method

Source: Internet
Author: User
Tags lenovo

The XML DOM standard was developed by the consortium. Many programming languages provide an API to support the XML DOM standard. In my previous article, I described how to use JavaScript to load and query XML documents. In this article, let me introduce you. The XmlDocument class in net. It supports and expands the 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 very large XML documents, you can use the XmlReader class to read. Because XmlReader uses steam (stream) to read files, it does not cause too much memory consumption. Here's a look at how to use the XmlDocument class.
(i) Loading
There are three ways to load XML more commonly:
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:

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= ' city= ' Beijing ' country= ' China ' name= ' Lenovo '/></customers > ";
XmlDocument xmlDoc3 = new XmlDocument ();
Xmldoc3.loadxml (str);


(b) Enquiry
You can use XPath for querying XML elements, attributes, and text. The specific definition can be see w3school.
You should first look at the XPath expression:

An expression Describe
NodeName Select all child nodes of this node.
/ Select from the root node.
// Selects the nodes in the document from the current node that matches the selection, regardless of their location.
. Select the current node.
.. Selects the parent node of the current node.
@ Select the attribute.


We mainly use two methods to query XML documents, selectnodes (XPath expression) and selectSingleNode (XPath expression).
SelectNodes returns a XmlNodeList object, that is, all XML nodes that conform to the XPath expression will be returned, and you need to iterate over the returned results.
selectSingleNode only returns the first node that conforms to an XPath expression, or returns NULL.
As an example of the following XML file, let's take a few demos:

Copy CodeThe code is as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<Customers>
<customer id= "city=" Beijing "country=" "China" Name= "Lenovo" >
<contact gender= "female" title= "support" >li li</contact>
</Customer>
<customer id= "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 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 the customer with ID 02:
XmlNode node = Xmldoc.selectsinglenode ("/customers/customer[@id = ' 02 ']");
Console.WriteLine (node. OuterXml);
The output is:
<customer id= "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 the contact that contains the contact name Li Li:
XmlNode node = Xmldoc.selectsinglenode ("/customers/customer/contact[text () = ' li Li ']");
Console.WriteLine (node. OuterXml);
Output Result:
<contact gender= "female" title= "support" >li li</contact>
4. Return the customer with the contact name Li Li. Note the difference with 3:
XmlNode node = Xmldoc.selectsinglenode ("/customers/customer[contact/text () = ' li Li ']");
Console.WriteLine (node. OuterXml);
Output Result:
<customer id= "city=" Beijing "country=" "China" Name= "Lenovo" >
<contact gender= "female" title= "support" >li li</contact>
</Customer>
5. (1) Get 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) Get 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);
(iii) Creation
For example, create the following XML document:

Copy CodeThe code is as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<Customers>
<customer id= "name=" Lenovo "country=" China "city=" Beijing ">
<contact title= "Support" gender= "female" >li 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 ("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: The XmlDocument class is a class that provides support for the XML DOM standard in the. Net API. You can use it to create and query XML documents. Because XmlDocument to load the contents of an XML document into memory, it is not appropriate to use the XmlDocument class for reading an XML document that is too large, and you can use XmlReader to complete the read.

C # manipulating XML documents using the XmlDocument class method

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.