O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

LINQ out of XML

The LINQ XML objects provide a standard assortment of LINQ functions that make moving data from those objects into IEnumerable objects simple. Using these functions, it’s about as easy to select data from the XML objects as it is from IEnumerable objects such as arrays and lists.

Because the XML objects represent special hierarchical data structures, they also provide methods to help you search those data structures. For example, the XElement object provides a Descendants function that searches the object’s descendants for elements of a certain type.

The following code extracts the x_all XElement object’s Customer descendants. It selects their FirstName and LastName attributes, and the balance saved as each element’s value.

Dim select_all = From cust In x_all.Descendants("Customer")
    Order By CDec(cust.Value)
    Select FName = cust.Attribute("FirstName").Value,
           LName = cust.Attribute("LastName").Value,
           Balance = cust.Value

The program can now loop through the select_all object just as it can loop through any other IEnumerable selected by a LINQ query.

The following query selects only customers with a negative balance:

Dim x_neg = From cust In x_all.Descendants("Customer")
    Where CDec(cust.Value) < 0
    Select FName = cust.Attribute("FirstName").Value,
           LName = cust.Attribute("LastName").Value,
           Balance = cust.Value

Example program LinqToXml, which is available for download on the book’s website, demonstrates these XML literals containing holes.

The following table describes ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required