24.3. Querying XML
In addition to enabling you to easily create XML, LINQ can also be used to query XML. We will use the following Customers XML in this section to discuss the XLINQ querying capabilities:
<Customers>
<Customer Name="Bob Jones">
<Order Product="Milk" Quantity="2"/>
<Order Product="Bread" Quantity="10"/>
<Order Product="Apples" Quantity="5"/>
</Customer>
...
</Customers>
The following two code snippets show the same query using VB.NET and C#, respectively. In both cases the customerXml variable (an XElement) is queried for all Customer elements, from which the Name attribute is extracted. The Name attribute is then split over the space between names, and the result is used to create a new Customer object.
VB.NET
Dim results = From cust In customerXml.<Customer> _
Let nameBits = cust.@Name.Split(" "c) _
Select New Customer() With {.FirstName = nameBits(0), _
.LastName = nameBits(1)}
C#
var results = from cust in customerXml.Elements("Customer")
let nameBits = cust.Attribute("Name").Value.Split(' ')
select new Customer() {FirstName = nameBits[0],
LastName=nameBits[1] };
As you can see, the VB.NET XML language support extends to enabling you to query elements using .<elementName> and attributes using .@attributeName. Figure 24-7 shows the IntelliSense for the customerXml variable, which shows three XML query options.
Figure 24.7. Figure 24-7
The second and third of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access