Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nodes by attribute that starts with... in C#

Tags:

c#

xml

I have this xml document and I want to select nodes by attribute that starts with '/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>

So in C#, I would do something like this:

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

Is this possible with C#?

Thanks!

like image 249
lionheart Avatar asked May 29 '12 14:05

lionheart


2 Answers

The simple starts-with function does what you need:

parentNode.SelectNodes("//table/tr/td/a[starts-with(@href, '/employees/')]")
like image 165
Steven Doggart Avatar answered Oct 05 '22 13:10

Steven Doggart


using pure LINQ you can do something like this

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

// now you can seelect any node by doing a combination of .Parent.Parent.....

like image 28
Parv Sharma Avatar answered Oct 05 '22 11:10

Parv Sharma