mim*_*011 2 c# xml linq linq-to-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>
Run Code Online (Sandbox Code Playgroud)
我在xml文件中有不一致的数据,需要一个xpath表达式来获取副本.
该规则是属性@ordnerno从item每个节点scool/schedule必须有一个独特的价值.如果我1 2 3 2在schedule的@orderno与值2的重复和不一致.
我使用XML linq表达式库
XDocument.Parse(structure)
.Descendants("item")
.Attributes("orderno")
.GroupBy(g => g.Value)
.Where(g => g.Count() > 1)
Run Code Online (Sandbox Code Playgroud)
我的解决方案不是最理想的,因为它将所有节点分组,schedule并且scool.
输出是1,2但在这种情况下1不是预期的.
我怎样才能解决我的问题?
逐个尝试逐项,如下所示:
XDocument.Parse(xml)
.Descendants("item")
.GroupBy(x => new { x.Parent.Name, orderno = x.Attribute("orderno").Value } )
.Where(g => g.Count() > 1);
Run Code Online (Sandbox Code Playgroud)
更新以选择@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();
Run Code Online (Sandbox Code Playgroud)