Introduction to C # LINQ to XML Application _c# Tutorial

Source: Internet
Author: User
Tags lenovo
The consortium has developed XML DOM standards. NET to support the standards of the consortium, the XmlDocument class was introduced from the 1.1 release. In my previous blog, I described how to use the XmlDocument class to manipulate XML documents. Later. NET introduced LINQ, so LINQ to XML came into being, so. NET, the XML document can be manipulated by using LINQ to XML as well as the standard of the XML DOM. Here's a quick overview of how to use LINQ to XML.
(i) Loading
There are three ways to load XML more commonly:
Copy Code code as follows:

public static XDocument Load (string uri);
public static XDocument Load (Stream stream);
public static XDocument Parse (string text);

The following code shows how to use them:
Copy Code code as follows:

public static XDocument Load (string uri);
The URI is the file name to load
var Doc1 = xdocument.load ("Xmlfile1.xml");
public static XDocument Load (Stream stream);
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);
XDocument Xdoc = Xdocument.load (ms);
public static XDocument Parse (string text);
String str = @ "<customers><customer id= ' city= ' Beijing ' country= ', ' name= ' Lenovo '/></customers > ";
var doc2 = xdocument.parse (str);

(ii) Enquiries
Let's take the following XML document for example:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<Customers>
<customer id= "city=" Beijing "country="
<order orderid= "1001" freight= "36.00"/>
<order orderid= "1003" freight= "61.50"/>
</Customer>
<customer id= "" 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 Code code as follows:

var result = from customer in Doc1. Descendants ("Customer")
Select customer. Value;
foreach (var s in result)
{
Console.WriteLine (s);
}

Output results:
Lenovo
Shell
2. Return the customer with ID 02 and city as Amsterdam:
Copy Code code as follows:

var result = (from customer in Doc1. Descendants ("Customer")
where (string) customer. Attribute ("id") = = "&&" (string) customer. Attribute ("city") = = "Amsterdam"
Select customer. Value). FirstOrDefault ();
Console.WriteLine (result);

Output results:
Shell
3. Find the Customer ID of order ID 1003 and its freight:
Copy Code code 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 results:
Customer id:01 freight:61.50
4. Query the sum of each customer's freight
Copy Code code 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 results:
Customer:lenovo Total freight:97.50
Customer:shell Total freight:222.65
5. Using LINQ to XML Join
Joins can be used in LINQ to XML and other LINQ providers, such as LINQ to Objects. The following code shows how to join an array and an XML file.
Copy Code code 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 results:
Customer Id:lenovo order:1001 freight:36,00
Customer Id:shell order:1002 freight:56,65
(iii) creating
For example, create the following XML document:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<Customers>
<customer id= "city=" Beijing "country=" "" "Name=" Lenovo ">
<order orderid= "1001" freight= "36.00"/>
</Customer>
</Customers>

Copy Code code as follows:

var doc = new XDocument (
New XElement ("Customers",
New XElement ("Customer",
New XAttribute ("id", "01"),
New XAttribute ("City", "Beijing"),
New XAttribute ("Country", "the"),
New XAttribute ("name", "Lenovo"),
New XElement ("Order",
New XAttribute ("OrderID", "1001"),
New XAttribute ("Freight", "36.00")
)
)
)
);
Doc. Save ("Test.xml");

Summarize:
1. XDocument provides a random read-write operation of an XML document in memory.
2. XDocument reads XML nodes using LINQ to XML.
3. You can transform XML into object by using a LINQ projection (projection).
4. Linq projections can transform XML into ienumerable<string>.
5. Linq projections can transform 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.