Xml literals provide an alternative syntax for LINQ to Xml queries in Visual Basic code. Let’s retake the first Xml document used in the “System.Xml.Linq
Namespace” section, which looks like the following but with a slight modification:
There is a Person
element that we want to be excluded. The goal is querying all Contact
elements whose age is greater than 40. Instead of recurring to the classical syntax, you can write the following code:
The preceding code uses new symbols for querying documents known as Xml Axis Properties. Table 28.3 summarizes Xml axis.
In other words, the preceding query can be described by this sentence: “Process all Contacts’ children Contact elements.” The difference with the Xml Axis Descendants Properties can be explained with another example. Consider the following document that is just a revalidation of the previous one:
Now each Contact
element has subelements. If you wanted to get a collection of all LastName
elements for all elements, you could use the Xml Axis Descendants property as follows:
It’s worth mentioning that such a query also includes results from the Person
element, because it exposes a LastName
attribute. So if you need to filter results depending on the root element, you should invoke the Axis Descendants property. Notice also how in both the previous code examples an explicit conversion is required when you need a comparison against non-String data. In this particular case the comparison is done against an integer number (40); therefore, you can invoke the Integer.Parse
method—because you expect that the Age
attribute contains the string representation of a number. Xml Axis properties provide therefore a simplified and cleaner way for querying Xml documents. Just remember that, as discussed in the previous section, you will need helper classes for mapping each XElement content into a .NET type to provide data-binding features to your code.
Option Strict On
is ImportantOne of the last code snippets had an explicit conversion using Integer.Parse
. If you set Option Strict On
and you forget to perform such a conversion, the compiler throws an exception requiring you to perform an appropriate conversion, which is always good. If you instead set Option Strict Off
, no conversion is required at compile time, but in all cases you encounter errors at runtime except if you assign the value of an attribute to a String variable. You should always keep Option Strict On.
3.16.69.106