2016-07-22 65 views
2

中查找重複的子節點我有下面的XML文檔XML文檔

<xml> 
    <schedule orderno = "1"> 
      <item orderno = "1" /> 
      <item orderno = "2" /> 
      <item orderno = "3" /> 
      <item orderno = "2" /> 
    </schedule> 
    <scool orderno = "2"> 
      <item orderno = "5" /> 
      <item orderno = "6" /> 
      <item orderno = "1" /> 
      <item orderno = "4" /> 
    </scool> 
</xml> 

我在XML文件中的數據不一致,需要一個XPath表達式得到重複。

規則是每個節點scool/schedule中來自item的屬性@ordnerno必須具有唯一值。如果我有1232 in schedule@orderno與值2重複且不一致。

我使用XML LINQ表達式庫

XDocument.Parse(structure) 
     .Descendants("item") 
     .Attributes("orderno") 
     .GroupBy(g => g.Value) 
     .Where(g => g.Count() > 1) 

我的解決辦法是次優的,因爲這組的所有節點,schedulescool

輸出是12,但在這種情況下1不是預期的。

我該如何解決我的問題?通過項目的母公司

+0

爲什麼你認爲的XPath會更好:

XDocument.Parse(xml) .Descendants("item") .GroupBy(x => new { x.Parent.Name, orderno = x.Attribute("orderno").Value }) .Where(g => g.Count() > 1); 

更新在任何嵌套級別選擇具有重複@orderno節點? –

+0

?我不明白你的答案.. linq表達式就像xpath。我正在用linq構建我的xpath表達式,但表達式並不完整。 – mimu1011

+1

啊。你得到的不是XPath,[XPath](https://en.wikipedia.org/wiki/XPath)是用於處理XML文檔部分的特定語言。您正在使用LINQ to XML,所以我建議您從問題中刪除對XPath的引用,如果這不是您真正想要的。 –

回答

6

嘗試組過,像這樣:

XDocument.Parse(xml) 
     .Root 
     .XPathSelectElements("//*[@orderno]") 
     .Cast<XElement>() 
     .GroupBy(x => new { x.Parent, orderno = x.Attribute("orderno").Value }) 
     .Where(g => g.Count() > 1) 
     .Dump(); 
+0

完全相同,謝謝!它的工作 – mimu1011

+0

我已經在數據庫中發現了一個新案例..表達式知道從父母ordnerno也是一個不一致的情況:(我已編輯的問題 – mimu1011

+0

@Mo_Code中的XML文件,所以你需要選擇父母等於'orderno'太對了,對吧? – lorond