在 XML 文档中查找重复的子节点

Find duplicate child nodes in XML document

我有以下 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/scheduleitem 的属性 @ordnerno 必须具有唯一值。如果我在 schedule 中有 1 2 3 2,则 @orderno 的值 2 重复且不一致。

我使用XML linq表达式库

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

我的解决方案不是最优的,因为它将所有节点分组,schedulescool

输出是 12 但在这种情况下 1 不是预期的。

我该如何解决我的问题?

也尝试按项目的父项分组,如下所示:

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

更新 到 select 个在任何嵌套级别上具有重复 @orderno 的节点:

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