[英]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.