C # Introduction to The LINQ to XML application

Source: Internet
Author: User

W3C has developed xml dom standards. To support W3C standards, the XmlDocument class has been introduced since version 1.1. In my previous blog, I introduced how to use the XmlDocument class to operate XML documents. Later,. Net introduced LINQ, so the emergence of LINQ to XML emerged. Therefore, in. Net, not only the W3C xml dom standard can be used, but also the XML document can be operated using LINQ to XML. Next, we will briefly introduce how to use LINQ to XML.
(1) Loading
There are three common methods to load XML: Copy codeThe Code is as follows: public static XDocument Load (string uri );
Public static XDocument Load (Stream stream );
Public static XDocument Parse (string text );

The following code demonstrates how to use them:Copy codeThe Code is as follows: // public static XDocument Load (string uri );
// Uri is the file name to be loaded
Var doc1 = XDocument. Load ("XMLFile1.xml ");
// Public static XDocument Load (Stream stream );
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 );
XDocument xDoc = XDocument. Load (MS );
// Public static XDocument Parse (string text );
String str = @ "<Customers> <Customer id = '01' city = 'beijing' country = 'China' name = 'lenovo '/> </Customers> ";
Var doc2 = XDocument. Parse (str );

(2) Query
The following XML document is used as an example:Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Customers>
<Customer id = "01" city = "Beijing" country = "China"> Lenovo
<Order OrderID = "1001" Freight = "36.00"/>
<Order OrderID = "1003" Freight = "61.50"/>
</Customer>
<Customer id = "02" city = "Amsterdam" country = "The Netherlands"> Shell
<Order OrderID = "1002" Freight = "56.65"/>
<Order OrderID = "1004" Freight = "65.50"/>
<Order OrderID = "1005" Freight = "100.50"/>
</Customer>
</Customers>

1. Return all Customer nodes:Copy codeThe Code is as follows: var result = from customer in doc1.Descendants ("Customer ")
Select customer. Value;
Foreach (var s in result)
{
Console. WriteLine (s );
}

Output result:
Lenovo
Shell
2. Return the customer whose id is 02 and city is Amsterdam:Copy codeThe Code is as follows: var result = (from customer in doc1.Descendants ("Customer ")
Where (string) customer. Attribute ("id") = "02" & (string) customer. Attribute ("city") = "Amsterdam"
Select customer. Value). FirstOrDefault ();
Console. WriteLine (result );

Output result:
Shell
3. Find the customer ID of order ID 1003 and its freight:Copy codeThe Code is as follows: var result = (from order in doc1.Descendants ("Order ")
Where order. Attribute ("OrderID"). Value = "1003"
Select new
{
CustomerID = order. Parent. Attribute ("id"). Value,
Freight = (decimal) order. Attribute ("Freight ")
}). FirstOrDefault ();
Console. WriteLine (string. Format ("Customer ID: {0} Freight: {1}", result. CustomerID, result. Freight ));

Output result:
Customer ID: 01 Freight: 61.50
4. query the total freight of each customerCopy codeThe Code is as follows: var result = from customer in doc1.Descendants ("Customer ")
Select new
{
CustomerName = customer. Value,
TotalFreight = customer. Descendants ("Order"). Sum (o => (decimal) o. Attribute ("Freight "))
};
Foreach (var r in result)
{
Console. WriteLine (string. Format ("Customer: {0} Total Freight: {1}", r. CustomerName, r. TotalFreight ));
}

Output result:
Customer: Lenovo Total Freight: 97.50
Customer: Shell Total Freight: 222.65
5. Use LINQ to XML Join
Join can be used in LINQ to XML and other LINQ providers, such as LINQ to Objects. The code below demonstrates how to Join an array with an XML file.Copy codeThe Code is as follows: string [] orders = {"1001", "2000", "1002 "};
Var result = from order in doc1.Descendants ("Order ")
Join selected in orders
On (string) order. Attribute ("OrderID") equals selected
Select new
{
CustomerName = order. Parent. Value,
OrderID = selected,
Freight = (decimal) (order. Attribute ("Freight "))
};
Foreach (var r in result)
{
Console. writeLine (string. format ("Customer ID: {0} Order: {1} Freight: {2}", r. customerName, r. orderID, r. freight ));
}

Output result:
Customer ID: Lenovo Order: 1001 Freight: 36,00
Customer ID: Shell Order: 1002 Freight: 56,65
(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" city = "Beijing" country = "China" name = "Lenovo">
<Order OrderID = "1001" Freight = "36.00"/>
</Customer>
</Customers>

Copy codeThe Code is as follows: var doc = new XDocument (
New XElement ("Customers ",
New XElement ("Customer ",
New XAttribute ("id", "01 "),
New XAttribute ("city", "Beijing "),
New XAttribute ("country", "China "),
New XAttribute ("name", "Lenovo "),
New XElement ("Order ",
New XAttribute ("OrderID", "1001 "),
New XAttribute ("Freight", "36.00 ")
)
)
)
);
Doc. Save ("test. xml ");

Summary:
1. XDocument provides random read/write operations on XML documents in memory.
2. XDocument uses LINQ to XML to read XML nodes.
3. You can use projection to convert XML into objects.
4. the XML can be converted into IEnumerable <String> by using the LINQ projection method.
5. LINQ projection can convert XML into XML in other formats.

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.