XPath SelectNodes

时间:2011-06-17 01:22:02

标签: c# .net html-agility-pack

我有:

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

我如何使用HtmlAgilityPack只选择href中包含'id'的项目?

输出:

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

谢谢,高级。

1 个答案:

答案 0 :(得分:1)

以下xpath表达式应选择具有a标记且包含文本“id”的所有href元素。

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

我可以使用以下代码在href属性中选择带有id的标签:

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