C # manipulating XML documents using the XmlDocument class method _c# Tutorial

Source: Internet
Author: User
Tags xpath lenovo
The consortium has developed XML DOM standards. Many programming languages provide APIs that support the standard of the XML Dom of the consortium. I have described in previous articles how to use JavaScript to load and query XML documents. In this article, let me introduce. NET in the XmlDocument class. It supports and expands the standard of the XML DOM for the consortium. It loads the entire XML document into memory and then operates on the XML document, so if the XML document content 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. 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 Code code as follows:

XmlDocument xmldoc = new XmlDocument ();
Xmldoc.load ("Xmlfile1.xml");
Entity retrievedannotation = _orgservice.retrieve ("annotation"
, the 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= ', ' name= ' Lenovo '/></customers > ";
XmlDocument xmlDoc3 = new XmlDocument ();
Xmldoc3.loadxml (str);

(ii) enquiries
You can use XPath for querying XML for elements, attributes, and text. A specific definition can be referred to W3school.
The first thing you should know about XPath expressions:
An 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 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, which means that all XML nodes that conform to XPath expressions will be returned, and you need to traverse the returned results.
selectSingleNode returns only the first node that conforms to an XPath expression, or returns NULL.
Take the following XML file for example, we'll do some demo:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<Customers>
<customer id= "city=" Beijing "country=" "" "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 results are:
<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 results are:
<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 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 the customer containing the contact name Li Li. Note the difference from 3:
XmlNode node = Xmldoc.selectsinglenode ("/customers/customer[contact/text () = ' li Li ']");
Console.WriteLine (node. OuterXml);
Output results:
<customer id= "city=" Beijing "country=" "" "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) creating
For example, create the following XML document:
Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<Customers>
<customer id= "Name=" "Lenovo" country= "" "city=" "Beijing" >
<contact title= "Support" gender= "female" >li li</contact>
</Customer>
</Customers>

Copy Code code as follows:

var xmldoc = new XmlDocument ();
Create the XML declaration
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 = "the";
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 is provided in the. Net API to support the standard of the XML Dom of the consortium. 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 XML documents that are too large to read, and can use XmlReader to complete the reading.

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.