LINQ to XML

Summary

LINQ to XML is a LINQ-enabled, in-memory XML programming interface.

LINQ to XML provides a new object model that is light weight and easy 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 LINQ. This integration enables you to write queries on the in-memory XML document to retrieve collections of elements and attributes. The XElement class represents the core of the entire LINQ to XML library.

LINQ to XML doesn't only provide for queries; it also provides for creating and modifying XML documents. The Parse method provided by the XElement class allows developers to build an XML document starting from a string.

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.

Using the SetElementValue method of XElement, we can update an element with a new value. The XElement class provides two methods to remove an element from an XML document: Remove and Remove Content.

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