[英]Intersect 2 Xml Files with XDocument in C#
我有 2 個 XML 文件,我想獲取兩個文件中的所有 XNodes ,僅基於它們相同的屬性“id”。 這是一個 XML 文件的樣子:
<parameters>
<item id="57">
<länge>8</länge>
<wert>0</wert>
</item>
<item id="4">
<länge>8</länge>
<wert>0</wert>
</item>
<item id="60">
<länge>8</länge>
<wert>0</wert>
</item>
</parameters>
給定第二個 XML 文件,如下所示:
<parameters>
<item id="57">
<länge>16</länge>
<wert>10</wert>
</item>
<item id="144">
<länge>16</länge>
<wert>10</wert>
</item>
</parameters>
現在我只想要 ID=57 的 XNode,因為它在兩個文件中都可用。 所以輸出應該是這樣的:
<item id="57">
<länge>8</länge>
<wert>0</wert>
</item>
我已經像這樣將兩個文件相交了:
aDoc = XDocument.Load(file);
bDoc = XDocument.Load(tmpFile);
intersectionOfFiles = aDoc.Descendants("item")
.Cast<XNode>()
.Intersect(bDoc.Descendants("item")
.Cast<XNode>(), new XNodeEqualityComparer());
當所有后代節點都相同時,這似乎才有效。 如果某些值不同,它將不起作用。 但是我需要讓它在相同的屬性上工作,值或后代無關緊要。
我還嘗試訪問屬性並將它們相交,但這也不起作用:
intersectionOfFiles = tmpDoc
.Descendants(XName.Get("item"))
.Attributes()
.ToList()
.Intersect(fileDoc.Descendants(XName.Get("item")).Attributes()).ToList();
我錯過了什么還是這是一個完全錯誤的方法?
提前致謝。
您應該創建自己的IEqualityComparer
來比較您想要的 XML 屬性:
public class EqualityComparerItem : IEqualityComparer<XElement>
{
public bool Equals(XElement x, XElement y)
{
return x.Attribute("id").Value == y.Attribute("id").Value;
}
public int GetHashCode(XElement obj)
{
return obj.Attribute("id").Value.GetHashCode();
}
}
然后將其傳遞給 XML 解析代碼:
var intersectionOfFiles = aDoc.Root
.Elements("item")
.Intersect(
bDoc.Root
.Elements("item"), new EqualityComparerItem());
我還更改了 XML 解析代碼的某些部分(XElement 而不是 XNode,因為“item”是 XML 元素,而“id”是 XML 屬性)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.