XPath text(), comment(), and processing-instruction() Guide
In XML XPath, node-test functions are specialized selectors used
within location steps to target non-element and non-attribute nodes
directly. This article explains how the text(),
comment(), and processing-instruction()
node-test functions operate, detailing their syntax, matching mechanics,
and practical applications for extracting specific nodes from an XML
document.
The text() Node Test
The text() node test matches any text node child of the
context node. In XML, plain character data contained inside elements is
represented as distinct text nodes rather than element nodes.
Operation: When evaluated,
text()selects individual text nodes directly contained by the parent element.Granularity: If an element contains mixed content (text mixed with child elements),
text()returns each isolated text chunk as a separate node in the node-set rather than concatenating them into a single string.Example:
//title/text()Given
<title>XML Guide</title>, this query selects the text node"XML Guide". Given<p>Hello <b>world</b>!</p>,//p/text()returns two distinct text nodes:"Hello "and"!".
The comment() Node Test
The comment() node test matches XML comment nodes within
the document hierarchy. XML comments are structured as
<!-- comment content -->.
Operation: It selects comment nodes regardless of their text content, allowing queries to inspect or extract metadata, documentation, or disabled markup retained inside comments.
Example:
//comment()This selects all comment nodes anywhere in the XML document.
/bookstore/book/comment()This selects comment nodes that are direct children of
<book>elements. The string value of the returned node corresponds to the text inside the<!--and-->delimiters.
The
processing-instruction() Node Test
The processing-instruction() node test matches
processing instruction (PI) nodes in the XML document. Processing
instructions take the format <?target data?> and
provide instructions to downstream processing applications.
Operation Without Arguments: When called as
processing-instruction(), it selects all processing instruction nodes within the evaluated axis.Operation With Arguments: It accepts an optional literal string argument representing the target name:
processing-instruction('target-name'). In this mode, it only matches processing instructions whose PITarget matches the specified argument.Example:
//processing-instruction()Selects every processing instruction in the document.
//processing-instruction('xml-stylesheet')Given
<?xml-stylesheet type="text/xsl" href="style.xsl"?>, this query selectively matches only the stylesheet processing instruction node.
Summary of Behavioral Differences
text()operates strictly on character data nodes and accepts no arguments.comment()operates strictly on XML comment nodes and accepts no arguments.processing-instruction()targets processing instructions and allows optional argument filtering based on the instruction’s target identifier.