Reputation: 14155
I have following html structure
<div class="ac_x">
<h3>
<a href="">Title</a>
</h3>
<a class="">
<img title="" />
</a>
<dl>
<dt class="">Person</dt>
<dd class="">
<dt class="ac_i_ard">Address</dt>
<dd class="ac_i_ard">
<a href="">Target text</a>
</dd>
</dl>
</div>
I'm selecting Title using
var nodes = htmlDoc.DocumentNode.SelectNodes(@"//div[@class='ac_x']/h3/a")
.Cast<HtmlAgilityPack.HtmlNode>().
.Select ....
Now I want to programmatically select next Target text under <dd class="ac_i_ard">
I tried with
node[0].SelectSingleNode(@"../dl/dd[2]/a");
but obviously I'm not selecting node
Object reference not set to an instance of an object.
how to select node (Target text) programatically from already selected node ?
Upvotes: 0
Views: 80
Reputation: 89295
Another problem is the first <dd>
tag is not closed. Therefore all of the following sibling are interpreted as child by HtmlAgilityPack. That's why the following works :
var n = node.SelectSingleNode(@"../following-sibling::dl/dd/dd[@class='ac_i_ard']/a");
or a bit simpler way :
var n = node.SelectSingleNode(@"../following-sibling::dl//dd[@class='ac_i_ard']/a");
Upvotes: 1
Reputation: 8781
var rootNodes = htmlDoc.DocumentNode.SelectNodes(@"//div[@class='ac_x']")
foreach(var n in rootNodes)
{
var titleNode = n.SelectSingleNode(@"h3/a");
var ddNodes = n.SelectNodes(@"dl/dd[@class='ac_i_ard']]/a");
}
Upvotes: 1
Reputation: 7173
you could use
../../dl/dd[@class='ac_i_ard']/a
or
../following-sibling::dl/dd[@class='ac_i_ard']/a
Upvotes: 1