Getting the text from a node using HtmlAgilityPack

c# html-agility-pack xpath

Question

I have the following HTML:

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

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();
doc.LoadHtml(myHtml);
doc.DocumentNode.SelectSingleNode("??????");

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.


Popular Answer

/div[@class='top']/p[.='Blah.']/following-sibling::node()

or

/div[@class='top']/node()[not(self::p)]



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why