Introduction to C LINQ to XML applications

  • 2020-05-09 19:04:01
  • OfStack

W3C has developed the XML DOM standard,.Net has introduced the XmlDocument class since version 1.1 to support the W3C standard. In my previous blog post, I showed you how to use the XmlDocument class to manipulate XML documents. Later, LINQ was introduced into.Net, and LINQ to XML came into being. Therefore, in.Net, not only can W3C XML DOM standard be used, but also LINQ to XML can be used to operate XML documents. Here is a brief introduction to how to use LINQ to XML.
(1) loading
There are three common ways to load XML:
 
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:
 
// public static XDocument Load(string uri); 
// uri  Is the file name to load  
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
Let's take the following XML document as an example:
 
<?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:
 
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 customer with id = 02 and city = Amsterdam:
 
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 results:
Shell
3. Find customer ID of order ID 1003 and its freight:
 
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 freight for each customer
 
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. Use LINQ to XML Join
Join can be used for LINQ to XML and other LINQ providers, such as LINQ to Objects. The following code shows how to combine 1 array with 1 XML file Join.
 
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
(3) creation
For example, create the following XML document:
 
<?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> 

 
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"); 

Conclusion:
1. XDocument provides random reads and writes to XML documents in memory.
2. XDocument USES LINQ to XML to read XML nodes.
3. You can convert XML to Object by LINQ projection (projection).
4. LINQ projection transforms XML to IEnumerable < String > .
5. LINQ projection can convert XML to XML in other formats.

Related articles: