【问题标题】:Find duplicate child nodes in XML document在 XML 文档中查找重复的子节点
【发布时间】:2016-07-22 11:10:42
【问题描述】:

我有以下 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必须具有唯一值。如果我在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 不是预期的。

我该如何解决我的问题?

【问题讨论】:

  • 为什么你认为 XPath 会更好?
  • ?我不明白你的回答.. linq 表达式就像 xpath。我正在用 linq 构建我的 xpath 表达式,但表达式不完整。
  • 啊。您所拥有的不是 XPath,XPath 是一种用于寻址 XML 文档部分的特定语言。您正在使用 LINQ to XML,所以如果这不是您真正想要的,我建议您从问题中删除对 XPath 的引用。
  • //item[@orderno = preceding::item/@orderno]
  • @splash58 你的 xpath 表达式和我的 linq 表达式完全一样

标签: c# xml linq linq-to-xml


【解决方案1】:

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

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

更新以选择在任何嵌套级别上具有重复 @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();

【讨论】:

  • 我在数据库中发现了一个新案例.. 表达式知道来自父级的 ordnerno 组,这也是一个不一致的案例:( 我已经编辑了问题中的 xml 文件
  • @Mo_Code 所以你也需要选择具有相同orderno 的父母,对吧?
  • 没错,我也需要选择具有相同 ordnerno 的父母。我也需要比较父节点 orderno ( schedule 和 scool )
  • @Mo_Code 我猜这是父元素属性名称中的拼写错误,应该是 orderno,而不是 ordnerno(看起来像多余的 n)?如果是这样,请参阅更新的答案。如果没有,告诉我,我会根据父属性名称中的n 更新答案。
  • 它的订单号..这是我的一个错误..抱歉
猜你喜欢
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多