SelectSingleNode returns false result in foreach

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(content); var nodes = doc.DocumentNode.SelectNodes("//div[@class=\"noprint res\"]/div"); if (nodes != null) { foreach (HtmlNode data in nodes) { // Works but not what I want MessageBox.Show(data.InnerHtml); // Should work ? but does not ? MessageBox.Show(data.SelectSingleNode("//span[@class=\"pp-place-title\"]").InnerText); } } 

I am trying to parse the results of HTML, the starting node for foreach, works as expected, and gives me a result of 10 elements that match me.

When I get into foreach, if I output the internal html of the data element, it displays the correct data, but if I post SelectSingleNode, it will always display data from the first element from foreach, is this normal behavior or am I doing something wrong?

To solve the problem, I had to create a new html inside foreach for each data item like this:

 HtmlAgilityPack.HtmlDocument innerDoc = new HtmlAgilityPack.HtmlDocument(); innerDoc.LoadHtml(data.InnerHtml); // Select what I need MessageBox.Show(innerDoc.DocumentNode.SelectSingleNode("//span[@class=\"pp-place-title\"]").InnerText); 

Then I get the correct data for each item.

The page I was trying to get data to was http://maps.google.com/maps?q=consulting+loc:+US if you want to try and see what happens for you.

Basically I read the left column for company names and this is happening.

+4
source share
1 answer

By running the XPath expression with // , you search the entire document that contains the data node.

You can use ".//[...]" only for checking nodes inside data .

+9
source

Source: https://habr.com/ru/post/1412554/


All Articles