繁体   English   中英

如何在C#中按以...开头的属性选择节点

[英]How to select nodes by attribute that starts with… in C#

我有这个xml文档,我想按'/ employees /'开头的属性选择节点。

<table>
  <tr>
    <td>
      <a href="/employees/1.html" title="Employee 1">Employee 1</a>
    </td>
    <td>Robert</td>
  </tr>
  <tr>
    <td>
      <a href="/employees/2.html" title="Employee 2">Employee 2</a>
    </td>
    <td>Jennifer</td>
  </tr>
</table>

所以在C#中,我会做这样的事情:

parentNode.SelectNodes("//table/tr/th/a[@href='/employees/.....']")

这可能与C#有关吗?

谢谢!

简单的starts-with功能可以满足您的需求:

parentNode.SelectNodes("//table/tr/td/a[starts-with(@href, '/employees/')]")

使用纯LINQ你可以做这样的事情

var doc = XDocument.Parse("YOUR_XML_STRING");
var anchors = from e in doc. Descendants("a") where e.Attribute("href").Value.StartsWith("/employee/") select e;

//现在你可以通过组合.Parent.Parent看到任何节点.....

那么,这样的事情呢?

var xml = @"<table>
  <tr>
    <td>
      <a href=""/employees/1.html"" title=""Employee 1"">Employee 1</a>
    </td>
    <td>Robert</td>
  </tr>
  <tr>
    <td>
      <a href=""/employees/2.html"" title=""Employee 2"">Employee 2</a>
    </td>
    <td>Jennifer</td>
  </tr>
</table>";
var doc = new XmlDocument();
doc.LoadXml(xml);

var employees = doc.SelectNodes("/table/tr/td/a[starts-with(@href, '/employees/')]");
DoWhatever(employees);

当然,您可以将XML加载到XDocument实例中,并使用XPathSelectElements方法使用表达式进行搜索。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM