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

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!

+6
source share
4 answers

The simple starts-with function does what you need:

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

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 see any node by doing .Parent.Parent .....

+3
source

So, something like this?

 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); 
+1
source

Of course, you can load your XML into an XDocument instance and use XPathSelectElements to search using your expression.

0
source

Source: https://habr.com/ru/post/916918/


All Articles