in reply to XML::LibXML::XPathContext->string_value - should ALL of the descendant's text be there?
I get a nodeset, start walking through it and getting text out, but when it comes out, for each node I get the text contained in node element AND the text of all of it's descendants (contained elements).
This makes sense to me. Consider this piece of HTML: <p>Hello, <b>World</b>!</p> - the <p> element has three child nodes: a text node ("Hello, "), the <b> element, and another text node ("!"). But if you ask the question "what text is contained in that paragraph?" then wouldn't the natural answer be "Hello, World!" instead of "Hello, !"? Otherwise, what question are you asking? If it's "what are the children of this <p> element that are text nodes", you'll have to code that explicitly, and you may get any number of text nodes (in the aforementioned example, it's two, but consider that any whitespace like newlines and indentation are text nodes too, e.g. the <body> in your example has three text children, all whitespace). Two ways to do that are to iterate over the childNodes of a node, checking their nodeType for XML_TEXT_NODE and XML_CDATA_SECTION_NODE. Or, use an XPath expression like '//p/child::text()'. OTOH, event-based parsers will return nodes as they encounter them. Perhaps you could explain what you're trying to do and what your expected output is?
$node->string_value();
Note this method is undocumented (there's a method with that name in XML::LibXML::NodeList, but your $nodes are XML::LibXML::Elements), you should use textContent instead.
Note that you don't need XML::LibXML::XPathContext unless the document you're parsing contains namespaces; the regular XML::LibXML::Node has a findnodes too.
Minor edits.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: XML::LibXML::XPathContext->string_value - should ALL of the descendant's text be there?
by bobn (Chaplain) on Aug 09, 2020 at 00:11 UTC | |
by haukex (Archbishop) on Aug 09, 2020 at 08:27 UTC | |
by bobn (Chaplain) on Aug 10, 2020 at 06:01 UTC |