htmlagilitypack using SelectSingleNode

c# html-agility-pack selectsinglenode xpath

Question

I've been trying to get the value of below using HtmlAgilityPack but without success. I'm using SelectSingleNode.

Here is my html.

<html>
<body>
    <table>
        <tr><td>One</td></tr>       
    </table>
</body>
</html>

And below is the codebehind.

HtmlDocument doc = new HtmlDocument();
doc.Load("C:\\test.html");

HtmlNode test = doc.DocumentNode.SelectSingleNode("/html/body/table/tbody/tr/td");
Console.WriteLine(test.InnerHtml);

The test (HtmlNode) variable is null.

How am I going to get the value inside which is One.

1
0
11/5/2014 5:09:08 PM

Accepted Answer

As shown your sample does not have tbody node so your XPath would return no nodes (null for SelectSingleNode).

Fix:

HtmlNode test = doc.DocumentNode.SelectSingleNode("/html/body/table/tr/td");

Debugging tip: build XPath slowly and check each result/child nodes:

     "/html/body/table/" - some children
     "/html/body/table/tbody/"  - null
     "/html/body/table/tr/" - some children
     "/html/body/table/tr/td" - score
1
11/5/2014 5:14:13 PM

Popular Answer

From Using XPath in SelectSingleNode: Retrieving individual element from XML if it's present you need to use text():

var test = doc.DocumentNode.SelectSingleNode("/html/body/table/tr/td/text()");

Also, you need to remove tbody. There is no tbody in your html.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow