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 ...