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

时间:2012-05-29 14:42:13

标签: c# xml

我有这个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#可以实现吗?

谢谢!

4 个答案:

答案 0 :(得分:21)

简单的starts-with函数可以满足您的需求:

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

答案 1 :(得分:3)

使用纯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 .....

来选择任何节点

答案 2 :(得分:1)

那么,这样的事情呢?

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);

答案 3 :(得分:0)

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

相关问题