Using HtmlAgilityPack to get the text from a node

c# html-agility-pack xpath


I have the following HTML:

<div class="top">
    I want <em>this</em> text.

What is the XPath notation to extract the string "I want <em>this</em> text."? EDIT: I don't necessarily want a single XPath expression to extract the string. Selecting multiple nodes, and iterating over them to produce the sentence, would be great as well.

HtmlDocument doc = new HtmlDocument();
11/1/2010 9:53:52 PM

Accepted Answer

What do you want to extract, nodes or a string?

If you want nodes, "I want <em>this</em> text." is an XML fragment consisting at the top level of two text nodes and an <em> element, which has a text node child. Since it has multiple nodes at the top level, you need to use SelectNodes("xpath expression a la @Alejandro") rather than SelectSingleNode() to extract them.

If you want a string, again you need to use SelectNodes(); and then iterate over the selected nodes and concatenate the outerHTML of each one. See here for a good example of something similar.

Also, it's a little unclear from your example what XPath expression would in general give you what you want. E.g. do you want everything after the initial <p>...</p> under <div class="top">? Or do you want all text under the <div> except all <p> elements? Or maybe something else? Of course if @Alejandro's XPath expressions work for you then it's already well-specified enough.

11/1/2010 9:58:31 PM

Popular Answer




Related Questions


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