繁体   English   中英

VB.NET XML Linq获取后代

[英]VB.NET XML Linq Get Descendants

我正在尝试使用LINQ来获取某些子元素的值。 这是XML文件:

<?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个值作为一个长字符串返回。 例如,巧克力BarChocolate Buttons热巧克力。 这不是很有用,因为我需要将这些单独添加到我的数据表中(以后)。

这是我目前拥有的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 element.@name = "Chocolate"
                                                Select element
For Each Ele In LinqQuery
   RichTextBox1.AppendText(Ele.Value & ControlChars.NewLine)
Next

哪个返回

Chocolate BarChocolate ButtonsHot Chocolate

在文本框中。

我如何获取它以分别返回每个值(因此将它们放在新行中)

非常感谢-希望这有意义,这是我第一次使用XML! 还允许使用其他方法,他们乐于聆听其他想法和技术。

问题是您要选择配方元素而不是所有成分元素。 当您输出父元素的Value时,它只是将所有子元素的文本值串联在一起,这就是您所看到的。

解决此问题的一种简单方法是更改​​此行:

Dim LinqQuery As IEnumerable(Of XElement) = From element In Doc.Descendants
                                                Where element.@name = "Chocolate"
                                                Select element

对此:

Dim LinqQuery As IEnumerable(Of XElement) = From element In Doc.Root.Descendants
                                                Where element.Parent.@name = "Chocolate"
                                                Select element

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM