[英]C# How to select all nodes of xml that have matching values
以下是我嘗試開始的xml和xml結果的示例。 我要找出的不是如何創建所需的xml,而是如何獲取具有相同起始值的所有匹配節點。 例如,在下面的示例中,您將看到xml有蘋果,有兩個帶有蘋果的節點。 我想找到所有這些節點,然后再創建一個自定義xml。
如何循環查找xml的所有節點,然后在同一節點級別上找到具有匹配值的所有結果?
<?xml version="1.0"?>
<results>
<result>
<fruit>apples</fruit>
<price>0</price>
</result>
<result>
<fruit>pears</fruit>
<price>1</price>
</result>
<result>
<fruit>apples</fruit>
<price>2</price>
</result>
</results>
<?xml version="1.0"?>
<results>
<result>
<fruit>apples</fruit>
<prices>
<price>0</price>
<price>2</price>
</prices>
</result>
<result>
<fruit>pears</fruit>
<prices>
<price>1</price>
</prices>
</result>
</results>
您可以使用XDocument完成此操作。 不要忘記導入。
using System.Xml.Linq;
using System.Xml.XPath;
載入文件
XDocument doc = XDocument.Load("C:\\t\\My File2.txt");
創建包含結果元素數組的列表
List<XElement[]> multipleElements = doc .XPathSelectElements("results/result") .GroupBy(result => result.Element("fruit").Value) .Select(groupContent => groupContent.ToArray()) .ToList();
===========結果===================
List [0] { apples,apples}
List [1] { pear }
我測試過的XML:
<?xml version="1.0"?> <results> <result> <fruit>apples</fruit> <price>0</price> </result> <result> <fruit>pears</fruit> <price>1</price> </result> <result> <fruit>apples</fruit> <price>2</price> </result> </results>
此VB代碼創建所需的輸出。 它選擇結果作為結果並按水果值排序,然后進行簡單循環以創建所需的輸出。
Dim xe As XElement
' to load from a file
' Dim yourpath As String = "your path here"
'xe = XElement.Load(yourpath)
' for testing
xe = <results>
<result>
<fruit>apples</fruit>
<price>0</price>
</result>
<result>
<fruit>pears</fruit>
<price>1</price>
</result>
<result>
<fruit>apples</fruit>
<price>2</price>
</result>
</results>
Dim oxe As XElement = <results></results>
Dim rsltproto As XElement = <result>
<fruit></fruit>
<prices></prices>
</result>
Dim rslt As XElement
Dim fruit As String
'select all <result> order by fruit values
Dim allfruits As IEnumerable(Of XElement) = xe...<result>.OrderBy(Function(el) el.<fruit>.Value)
'simple loop to create new XML
For Each el As XElement In allfruits
If el.<fruit>.Value <> fruit Then
If rslt IsNot Nothing Then
oxe.Add(rslt)
End If
fruit = el.<fruit>.Value
rslt = New XElement(rsltproto)
rslt.<fruit>.Value = fruit
End If
rslt.<prices>.LastOrDefault.Add(el.<price>)
Next
If rslt IsNot Nothing Then
oxe.Add(rslt)
End If
' to save file
' xe.Save(yourpath)
這是對上面Timon答案的簡單更改
var doc = XDocument.Load(@"<path>\test.xml");
var fruitPrices = doc.XPathSelectElements("results/result")
.Select(d => new {
Fruit = d.Element("fruit").Value,
// TODO: parse to int if required
Price = d.Element("price").Value
})
.GroupBy(f => f.Fruit)
.Select(g => new {Fruit = g.Key, Prices = g.Select(x => x.Price)})
.ToList();
在LinqPad中,這給出了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.