Introducing LINQ to XML
LINQ to XML provides the power of the DOM and the expressiveness of
XPath and XQuery through LINQ extension methods to manage and query in-memory
XML nodes. It uses the latest enhancements of .NET languages, such as anonymous
methods, generics, nullable types, and so forth. Consider the following
introductory sample XML document:
Listing 6-1 shows how you can
build such a document with LINQ to XML syntax using C#.
Listing 6-1: A
sample of XML functional construction
XDocument customer =
new XDocument(
new XDeclaration("1.0", "UTF-16", "yes"),
new XElement("customer",
new XAttribute("id", "C01"),
new XElement("firstName", "Paolo"),
new XElement("lastName", "Pialorsi"),
new XElement("addresses",
new XElement("address",
new XAttribute("type", "email"),
"paolo@devleap.it"),
new XElement("address",
new XAttribute("type", "url"),
"http://www.devleap.it/"),
new XElement("address",
new XAttribute("type", "home"),
"Brescia - Italy"))));
The preceding example is called “functional construction,” and it
reveals how it is simple and intuitive to define an XML nodes hierarchy with
the LINQ to XML API. As you can see, the code layout describes the final
hierarchical structure using nested constructors. A standard DOM approach
requires you to declare and collect many objects, while this new syntax uses a
single “hierarchical” statement to achieve this goal, allowing the developer to
focus on the final output XML structure rather than on DOM rules.
As you saw in
Chapter 3, “Visual
Basic 9.0 Language Features,” Visual Basic 9.0 language enhancements
introduce a new feature called XML literals that makes
it easier to write and read XML contents. In fact, the previous example, when
written in Microsoft Visual Basic 9.0, looks like the excerpt shown in
Listing 6-2.
Listing 6-2: A
sample of Visual Basic 9.0 XML literals
Dim customerXml As XDocument = _
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<customer id="C01">
<firstName>Paolo</firstName>
<lastName>Pialorsi</lastName>
<addresses>
<address type="email">paolo@devleap.it</address>
<address type="url">http://www.devleap.it/</address>
<address type="home">Brescia - Italy</address>
</addresses>
</customer>
The power and expressiveness of this syntax is truly evident. We
write pure XML code, even if it is inside a Visual Basic 9.0 piece of code.
Also, querying XML with LINQ to XML is really simple. In the following sample
code, we enumerate all the address tags of a given
customer, using C#:
Using Visual Basic 9.0, this query can be written using a more
intuitive syntax, like the following one:
We will come back to this fancy syntax later, but now just
notice that once again we are using an XML-like syntax within Visual Basic 9.0
code. From the next section to the end of this chapter, we will cover all the
features of LINQ to XML.