Reputation:
I'm crawling a website using htmlagilitypack c#:
i have in the source code of an html page
....
<p>this a p that come before h3</p>
....
....
<h3>this h3 </h3>
<p>first p after h3</p>
....
<p>seconde p after h3</p>
i want to to all get all Ps that come after
is there a way to use a where to filter Ps using position.
where (position(p)>position(h3))
Upvotes: 1
Views: 2069
Reputation: 11
Try the following code:
var htmlText = "source code of your html page";
var htmlDoc.LoadHtml(htmlText);
var h3= htmlDoc.DocumentNode.SelectNodes("//h2");
var lineNum = h3[0].Line;
var p = htmlDoc.DocumentNode.SelectNodes("//p").Where(x => x.Line > lineNum);
Upvotes: 1
Reputation: 134611
You could use a helper method such as this:
static IEnumerable<HtmlNode> FilteredTakeWhile(
HtmlNode root,
Func<HtmlNode, bool> predicate,
Func<HtmlNode, bool> takePredicate)
{
for (var currentNode = root.NextSibling;
currentNode != null && takePredicate(currentNode);
currentNode = currentNode.NextSibling)
{
if (predicate(currentNode))
yield return currentNode;
}
}
Then to use it:
var h3 = doc.DocumentNode.SelectSingleNode("h3");
// take all "p" nodes while we haven't reached the next "h3" node
var query = FilteredTakeWhile(h3, node => node.Name == "p", node => node.Name != "h3");
Upvotes: 2