XPath SelectNodes

.net c# html-agility-pack

Question

I have:

<div id="foo">
<a href="/xxx.php"> xx </a>
<a href="/xy.php"> xy </a>
<a href="/uid.php?id=123"> 123 </a>
<a href="/uid.php?id=344"> 344 </a>
</div>

I how select only items containing 'id' in href using HtmlAgilityPack?

with Output:

 <a href="/uid.php?id=123"> 123 </a>
    <a href="/uid.php?id=344"> 344 </a>

Thanks,Advanced.

Accepted Answer

The following xpath expression should select all a elements that have an href tag that contains the text "id".

var xpathExpression = "//a[contains(@href, 'id')]";

I was able to select the a tags with id in the href attribute using the following code:

var htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(
  @"<div id=""foo"">
    <a href=""/xxx.php""> xx </a>
    <a href=""/xy.php""> xy </a> 
    <a href=""/uid.php?id=123""> 123 </a>
    <a href=""/uid.php?id=344""> 344 </a>
</div>");
var aTags = htmlDoc.DocumentNode.SelectNodes("//a[contains(@href, 'id')]");
foreach(var aTag in aTags)
Console.WriteLine(aTag.OuterHtml);



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why