select 包含几乎相同 ID 的内部 XML 节点

select Inner XML nodes which contains nearly same id

这是我的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>

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

我得到了这个

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

但是 returns Enumeration yielded no results.

使用 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 与 XML 的结构不匹配。您的查询假定根称为 root 但有一个 rootparent 而您没有考虑它。由于您只是在寻找 child 个节点,因此您甚至不需要引用它,只需遍历后代即可。

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

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