1

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("??????");
grautur
  • 29,955
  • 34
  • 93
  • 128

2 Answers2

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

or

/div[@class='top']/node()[not(self::p)]
  • @Alejandro, he's put the XPath inside SelectSingleNode(), but no single XPath expression will get him the result he wants. – LarsH Nov 01 '10 at 21:43
  • @Alejandro: This gives me "I want ", but not the rest of the sentence. @LarsH: It doesn't have to be SelectSingleNode, I'm just looking for any way to get the whole sentence (with the html still intact). – grautur Nov 01 '10 at 21:46
  • Oh, I see now. It gives me the entire sentence if I use SelectNodes() [as per LarsH's suggestion]. – grautur Nov 01 '10 at 22:02
  • @grautur: Yes, you have to use `SelectNodes()` (as @LarsH point out there is no web documentation aviable for Agility Pack). –  Nov 01 '10 at 22:07
1

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.

LarsH
  • 27,481
  • 8
  • 94
  • 152
  • I want to extract the string "`I want this text.`" – grautur Nov 01 '10 at 21:54
  • Using SelectNodes() and iterating over each node, if I have to. – grautur Nov 01 '10 at 21:55
  • @grautur: ok... see the example I linked to in my latest edit. I'm having a hard time finding documentation for the HTML Agility Kit ... do you know where it is? I downloaded a chm help file but it doesn't work in Windows 7 apparently. – LarsH Nov 01 '10 at 21:59
  • I got it now, thanks! I used Alejandro's expression. [I didn't realize I had to select multiple nodes, and didn't know that "OuterHtml" existed.] Your explanation was super helpful, though, so I'll accept yours. – grautur Nov 01 '10 at 22:05