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



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

使用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节点,因此您甚至不需要引用它,只需浏览后代即可。

您需要使用适当的条件。您的孩子都没有一个名为child_*的ID元素,因此您自然不会得到任何结果。使用starts-with功能并访问id 属性

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

最新更新