W3C formulated the XML DOM standard. In order to support W3C standards, .Net introduced the XmlDocument class since version 1.1. In my previous blog, I explained how to use the XmlDocument class to operate on XML documents. Later, LINQ was introduced in .Net, LINQ to XML came into being. Therefore, in .Net, you can not only use the W3C XML DOM standard, but also use LINQ to XML to operate XML documents. Let’s briefly introduce how to use LINQ to XML.
(I) Loading
There are three common methods to load XML:
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:
// public static XDocument Load(string uri);
// uri is the file name to be loaded
var doc1 = ("");
// 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 = (ms);
// public static XDocument Parse(string text);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
var doc2 = (str);
(II) Query
Our XML document below is an example:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer city="Beijing" country="China">Lenovo
<Order OrderID="1001" Freight="36.00" />
<Order OrderID="1003" Freight="61.50" />
</Customer>
<Customer 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 ("Customer")
select ;
foreach (var s in result)
{
(s);
}
Output result:
Lenovo
Shell
2. Return customer with id 02 and city is Amsterdam:
var result = (from customer in ("Customer")
where (string)("id") == "02" && (string)("city") == "Amsterdam"
select ).FirstOrDefault();
(result);
Output result:
Shell
3. Find out the customer ID of order ID 1003 and its freight:
var result = (from order in ("Order")
where ("OrderID").Value == "1003"
select new
{
CustomerID = ("id").Value,
Freight = (decimal)("Freight")
}).FirstOrDefault();
(("Customer ID: {0} Freight: {1}", , ));
Output result:
Customer ID: 01 Freight: 61.50
4. Query the sum of freights of each customer
var result = from customer in ("Customer")
select new
{
CustomerName = ,
TotalFreight = ("Order").Sum(o => (decimal)("Freight"))
};
foreach (var r in result)
{
(("Customer: {0} Total Freight: {1}", , ));
}
Output result:
Customer: Lenovo Total Freight: 97.50
Customer: Shell Total Freight: 222.65
5. Using LINQ to XML Join
Join 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.
string[] orders = {"1001", "2000", "1002"};
var result = from order in ("Order")
join selected in orders
on (string)("OrderID") equals selected
select new
{
CustomerName = ,
OrderID = selected,
Freight = (decimal)(("Freight"))
};
foreach (var r in result)
{
(("Customer ID: {0} Order:{1} Freight: {2}", , , ));
}
Output result:
Customer ID: Lenovo Order:1001 Freight: 36,00
Customer ID: Shell Order:1002 Freight: 56,65
(III) Create
Take creating the following XML document as an example:
<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer 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")
)
)
)
);
("");
Summarize:
1. XDocument provides random read and write operations on XML documents in memory.
2. XDocument uses LINQ to XML to read XML nodes.
3. You can convert XML to Object through LINQ projection.
4. LINQ casting can transform XML into IEnumerable<String>.
5. LINQ casting can transform XML into XML in other formats.
(I) Loading
There are three common methods to load XML:
Copy the 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 the codeThe code is as follows:
// public static XDocument Load(string uri);
// uri is the file name to be loaded
var doc1 = ("");
// 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 = (ms);
// public static XDocument Parse(string text);
string str = @"<Customers><Customer id='01' city='Beijing' country='China' name='Lenovo'/></Customers>";
var doc2 = (str);
(II) Query
Our XML document below is an example:
Copy the codeThe code is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
<Customer city="Beijing" country="China">Lenovo
<Order OrderID="1001" Freight="36.00" />
<Order OrderID="1003" Freight="61.50" />
</Customer>
<Customer 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 the codeThe code is as follows:
var result = from customer in ("Customer")
select ;
foreach (var s in result)
{
(s);
}
Output result:
Lenovo
Shell
2. Return customer with id 02 and city is Amsterdam:
Copy the codeThe code is as follows:
var result = (from customer in ("Customer")
where (string)("id") == "02" && (string)("city") == "Amsterdam"
select ).FirstOrDefault();
(result);
Output result:
Shell
3. Find out the customer ID of order ID 1003 and its freight:
Copy the codeThe code is as follows:
var result = (from order in ("Order")
where ("OrderID").Value == "1003"
select new
{
CustomerID = ("id").Value,
Freight = (decimal)("Freight")
}).FirstOrDefault();
(("Customer ID: {0} Freight: {1}", , ));
Output result:
Customer ID: 01 Freight: 61.50
4. Query the sum of freights of each customer
Copy the codeThe code is as follows:
var result = from customer in ("Customer")
select new
{
CustomerName = ,
TotalFreight = ("Order").Sum(o => (decimal)("Freight"))
};
foreach (var r in result)
{
(("Customer: {0} Total Freight: {1}", , ));
}
Output result:
Customer: Lenovo Total Freight: 97.50
Customer: Shell Total Freight: 222.65
5. Using LINQ to XML Join
Join 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 the codeThe code is as follows:
string[] orders = {"1001", "2000", "1002"};
var result = from order in ("Order")
join selected in orders
on (string)("OrderID") equals selected
select new
{
CustomerName = ,
OrderID = selected,
Freight = (decimal)(("Freight"))
};
foreach (var r in result)
{
(("Customer ID: {0} Order:{1} Freight: {2}", , , ));
}
Output result:
Customer ID: Lenovo Order:1001 Freight: 36,00
Customer ID: Shell Order:1002 Freight: 56,65
(III) Create
Take creating the following XML document as an example:
Copy the codeThe code is as follows:
<?xml version="1.0" encoding="utf-8"?>
<Customers>
<Customer city="Beijing" country="China" name="Lenovo">
<Order OrderID="1001" Freight="36.00" />
</Customer>
</Customers>
Copy the 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")
)
)
)
);
("");
Summarize:
1. XDocument provides random read and write operations on XML documents in memory.
2. XDocument uses LINQ to XML to read XML nodes.
3. You can convert XML to Object through LINQ projection.
4. LINQ casting can transform XML into IEnumerable<String>.
5. LINQ casting can transform XML into XML in other formats.