老树新芽 体验Visual Basic 9.0新功能(2)
除了构造XML,Visual Basic9.0也通过XML的后期绑定简化了访问XML结构。也就是,在VB代码中的标识符是在运行时和XML属性和元素绑定的。举例来说,我们可以打印出人口密度如下:
1. 使用child axis CountriesWithCapital.Country来从CountriesWithCapital XML结构获取所有的"Country"元素;
2. 使用attribute axis Country.@Density获取Country元素的"Density"属性;
3. 使用descendants axis Country...Latitude--在源代码中写三个点,获取Country元素的所有"Latitude"子元素,无论他们在层次结构中处于多深;
4. 使用extension indexer on IEnumerable(Of T)来选择结果序列中的第一个元素。
如果放在一起,代码如下:
·descendant axis表达式Country...Latitude(0)翻译成ElementAt(Country.Descendants(Latitude),0)的结合,返回所有Country任何层次的所有元素的集合对象。
For Each Dim Country In CountriesWithCapital.Country
Console.WriteLine("Density = "+ Country.@Density)
Console.WriteLine("Latitude = "+ Country...Latitude(0))
Next
当一个声明,赋值或者初始化是Object类型而不是其他指定的类型的时候,编译器知道对一般的对象使用后期绑定。同时,编译器液汁到当目标表达式是XElement, XDocument, or XAttribute的类型或者集合对象时使用后期绑定。
作为后期绑定的结果,编译器将如下翻译:
·child axis表达式CountriesWithCapital.Country 翻译成raw XLinq call CountriesWithCapital.Elements("Country"),返回所有名为"Country"的Country元素的子元素的集合对象;
·attribute axis 表达式Country.@Density 翻译成Country.Attribute("Density"),返回Country的名为"Density"的单个子属性;
0
相关文章