【问题标题】:select Inner XML nodes which contains nearly same id选择包含几乎相同 id 的内部 XML 节点
【发布时间】:2016-12-01 14:38:11
【问题描述】:

这是我的 XML..

<rootparent>
  <root>
    ...other nodes here.
    ...
    <parent>
      <child id="child_1">
        .some other nodes ..
      </child>  
      <child id="child_2">
        .some other nodes ..
      </child>  
      ...other nodes
    </parent>
  </root>
</rootparent>

我需要使用 LINQ to XML select all the child nodes where id like 'child_%'

我得到了这个的 xpath

string xPath="/root/parent/child[id='child_*']";
var x1 =xml.XPathSelectElement(xPath);
var x2 = _sourceDoc.Root.XPathEvaluate(xPath); 

但它返回Enumeration yielded no results

【问题讨论】:

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


【解决方案1】:

使用 xml linq:

string xml =
    "<rootparent>" +
        "<root>" +
         "<parent>" +
          "<child id=\"child_1\">" +
          "</child>" +
          "<child id=\"child_2\">" +
          "</child>" +
         "</parent" +
        "</root>" +
    "</rootparent>";

XDocument doc = XDocument.Parse(xml);

List<XElement> children = doc.Descendants("child")
    .Where(x => ((string)x.Attribute("id")).StartsWith("child_"))
    .ToList();

【讨论】:

  • 您这里没有使用 XPath,我需要使用 XPath 因为我正在尝试以更通用的方式进行操作。
  • 如果你想要一个通用的解决方案,你仍然可以使用 linq xml。只需使用 doc.Descendants() 而不是指定“孩子”。帖子标题说的是Linq,
  • @A_Name_Does_Not_Matter:如果您不打算接受 linq 解决方案,请不要这样标记它。它被标记为 linq-to-xml,所以你得到了一个 linq-to-xml 答案。
  • 您是否在代码中使用了 XPath,我需要使用它。我不想一一破解XPAth并找到节点。
【解决方案2】:

首先,您的 xpath 与 XML 的结构不匹配。您的查询假定根名为root,但有一个rootparent,您不考虑它。由于您只是在寻找child 节点,因此您甚至不需要引用它,只需遍历后代即可。

您需要使用适当的条件。您的孩子都不包含名为 child_* 的 id 元素,因此您自然不会得到任何结果。使用starts-with 函数并访问id 属性

//child[starts-with(@id, 'child_')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-24
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-19
    • 2010-10-10
    • 2015-05-08
    相关资源
    最近更新 更多