Javidan
Javidan

Reputation: 594

Cannot get HtmlNode with using XPath retrieved from same HtmlNode

There is property XPath of HtmlNode, if I get that and use it to get single node from root HtmlNode it gives me exception Expression must evaluate to a node-set.'

So here what I am doing:

HtmlNode someNode=getNode(rootNode);
HtmlNode foundNode=rootNode.SelectSingleNode(someNode.XPath);

Structure does not change during calls. Any clue why it is not working ? I get XPath like this: /html[1]/body[1]/main[1]/div[1]/div[1]/div[2]/form[1]/div[2]/#text[1]

Upvotes: 0

Views: 298

Answers (2)

Gianlucca
Gianlucca

Reputation: 1354

Without providing us with some code it's very difficult for us to figure out what the problem is.

If you just want to find a specific string, I would suggest you to use xpath functions, like this:

"//*[contains(text(), 'string you are looking for')]"

Upvotes: 0

Kent Kostelac
Kent Kostelac

Reputation: 2456

I think it mattered. Because first of your xpath is a mess and hard to maintain if they just change one small thing on their site. Any way below is the correct way of doing what you're trying to do.

HtmlNode n = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/main[1]/div[1]/div[1]/div[2]/form[1]/div[2]/text()[1]");

 Console.WriteLine(n.InnerText);

Easier way to get it is like this.

HtmlNode n = doc.DocumentNode.SelectSingleNode("//div[@class='alert alert-error'][string-length(normalize-space(text()))>0]");

Here we select the div-tag with a class attribute that equals 'alert alert-error'. But we only want it if it has a length that is greater than 0.

Upvotes: 1

Related Questions