The Mask
The Mask

Reputation: 17427

XPath SelectNodes

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.

Upvotes: 1

Views: 1683

Answers (1)

rsbarro
rsbarro

Reputation: 27339

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

Upvotes: 1

Related Questions