2014-01-07 38 views
1

我想用LINQ来获取一些子元素的值。这里是XML文件:VB.NET XML Linq获取后代

<?xml version="1.0" standalone="yes"?> 
<UserRecipes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <recipe name="Chocolate" portions="5"> 
    <ingredient quantity="500" unit="g">Chocolate Bar</ingredient> 
    <ingredient quantity="300" unit="g">Chocolate Buttons</ingredient> 
    <ingredient quantity="250" unit="g">Hot Chocolate</ingredient> 
    </recipe> 
    <recipe name="Cookies" portions="24"> 
    <ingredient quantity="4" unit="oz">Flour</ingredient> 
    <ingredient quantity="200" unit="g">Chocolate Buttons</ingredient> 
    <ingredient quantity="600" unit="g">Sugar</ingredient> 
    </recipe> 
    <recipe name="Cake" portions="22"> 
    <ingredient quantity="4" unit="oz">Flour</ingredient> 
    <ingredient quantity="4" unit="oz">Sugar</ingredient> 
    <ingredient quantity="4" unit="oz">Butter</ingredient> 
    <ingredient quantity="60" unit="n/a">Eggs</ingredient> 
</recipe> 
</UserRecipes> 

这样做的想法是能够检索特定配方中使用的成分。例如,如果用户选择“巧克力”,则它将检索“巧克力”配方中使用的所有成分 - 在这种情况下:巧克力棒,巧克力按钮和热巧克力。然而,目前,当我执行我的LINQ查询时,它将所有这3个值作为一个长字符串返回。例如。巧克力棒巧克力纽扣热巧克力。这不是很有用,因为我需要将这些单独添加到我的数据表(稍后)。

这里是VB.NET代码我目前有:

Dim Doc As XDocument = XDocument.Load("G:\Computing\!Recipe Test\XMLTest.xml") 
Dim LinqQuery As IEnumerable(Of XElement) = From element In Doc.Descendants 
               Where [email protected] = "Chocolate" 
               Select element 
For Each Ele In LinqQuery 
    RichTextBox1.AppendText(Ele.Value & ControlChars.NewLine) 
Next 

其中在文本框中返回

Chocolate BarChocolate ButtonsHot Chocolate 

我怎样才能得到它单独返回每个值(并因此把它们放在一个新行)

非常感谢 - 希望这是有道理的,这是我第一次用XML!替代方法也是允许的,更乐意倾听其他想法和技巧。

+0

是你的文本框设置为多行? – webdad3

回答

1

问题是,你选择的配方元素,而不是所有的成分元素。当你输出一个父元素的Value时,它简单地连接它所有子元素的文本值,这就是你所看到的。

一个简单的方法解决这个问题是要改变这一行:

Dim LinqQuery As IEnumerable(Of XElement) = From element In Doc.Descendants 
               Where [email protected] = "Chocolate" 
               Select element 

要这样:

Dim LinqQuery As IEnumerable(Of XElement) = From element In Doc.Root.Descendants 
               Where [email protected] = "Chocolate" 
               Select element 
+1

完美的作品。我会投票,但没有足够的声望。 – TeknoVenus