LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the .NET Framework programming languages.
LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory. You can query and modify the document, and after you modify it you can save it to a file or serialize it and send it over the Internet. However, LINQ to XML differs from DOM: It provides a new object model that is lighter weight and easier to work with, and that takes advantage of language improvements in Visual C# 2008.
The most important advantage of LINQ to XML is its integration with Language-Integrated Query (LINQ). This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes. The query capability of LINQ to XML is comparable in functionality (although not in syntax) to XPath and XQuery. The integration of LINQ in Visual C# 2008 provides stronger typing, compile-time checking, and improved debugger support.
Another advantage of LINQ to XML is the ability to use query results as parameters to XElement and XAttribute object constructors enables a powerful approach to creating XML trees. This approach, called functional construction, enables developers to easily transform XML trees from one shape to another.
For example, you might have a typical XML purchase order as described in Sample XML File: Typical Purchase Order (LINQ to XML). By using LINQ to XML, you could run the following query to obtain the part number attribute value for every item element in the purchase order:
IEnumerable<string> partNos =
from item in purchaseOrder.Descendants("Item")
select (string) item.Attribute("PartNumber");
In Visual Basic, the same query can be written as follows:
Dim partNos = _
From item In purchaseOrder...<Item> _
Select item.@PartNumber
As another example, you might want a list, sorted by part number, of the items with a value greater than $100. To obtain this information, you could run the following query:
IEnumerable<XElement> partNos =
from item in purchaseOrder.Descendants("Item")
where (int) item.Element("Quantity") *
(decimal) item.Element("USPrice") > 100
orderby (string)item.Element("PartNumber")
select item;
In Visual Basic, the same query can be written as follows:
Dim partNos = _
From item In purchaseOrder...<Item> _
Where (item.<Quantity>.Value * _
item.<USPrice>.Value) > 100 _
Order By item.<PartNumber>.Value _
Select item
In addition to these LINQ capabilities, LINQ to XML provides an improved XML programming interface. Using LINQ to XML, you can:
Load XML from files or streams.
Serialize XML to files or streams.
Create XML from scratch by using functional construction.
Query XML using XPath-like axes.
Manipulate the in-memory XML tree by using methods such as Add, Remove, ReplaceWith, and SetValue.
Validate XML trees using XSD.
Use a combination of these features to transform XML trees from one shape into another.