I'm using xsl:stylesheet
Processing Instruction in my XML. Is there anyway to select this PI using XPath ? If so how ?
In XPath, path expression is used to select nodes or node-sets in an XML document. The node is selected by following a path or steps. Let's take an example to see the syntax of XPath. Here, we take an XML document.
XPath is a language for addressing specific parts of a document. XPath models an XML document as a tree of nodes. An XPath expression is a mechanism for navigating through and selecting nodes from the document. An XPath expression is, in a way, analogous to an SQL query used to select records from a database.
Use processing-instruction()
node-test.
In general, a processing instruction can be selected using the processing-instruction()
node test.
More specifically, one can include as argument the name (target) of the wanted PI node.
Use:
/processing-instruction('xml-stylesheet')
This selects any processing instruction with name xsl-stylesheet
that is defined at the global level (is sibling of the top element).
Do note that xsl:stylesheet
is an invalid PI target for a PI. A colon ':'
is used to delimit a namespace prefix from the local name -- however a processing instruction target cannot belong to a namespace. As per the W3c XPath Specification:
"A processing instruction has an expanded-name: the local part is the processing instruction's target; the namespace URI is null."
Also according to the W3C document: "Associating Style Sheets with XML documents 1.0", the target of the PI that associates a stylesheet to an XML document must be: "xml-stylesheet"
-- not "xsl:stylesheet"
or "xsl-stylesheet"
.
Here is a complete example:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/processing-instruction('xml-stylesheet')"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied against the following XML document:
<?xml-stylesheet type="text/xsl" href="test"?>
<Books>
<Book name="MyBook" />
</Books>
the XPath expression is evaluated and the selected PI node is output:
<?xml-stylesheet type="text/xsl" href="test"?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With