问题
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("??????");
回答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.
回答2:
/div[@class='top']/p[.='Blah.']/following-sibling::node()
or
/div[@class='top']/node()[not(self::p)]
来源:https://stackoverflow.com/questions/4072965/getting-the-text-from-a-node-using-htmlagilitypack