Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the XPath expression to select a Processing instruction?

Tags:

xml

xslt

xpath

I'm using xsl:stylesheet Processing Instruction in my XML. Is there anyway to select this PI using XPath ? If so how ?

like image 394
Chandu Avatar asked Feb 24 '12 07:02

Chandu


People also ask

What will be the XPath expression to select?

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.

What is an XPath expression?

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.


2 Answers

Use processing-instruction() node-test.

like image 126
Kirill Polishchuk Avatar answered Sep 28 '22 03:09

Kirill Polishchuk


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"?>
like image 24
Dimitre Novatchev Avatar answered Sep 28 '22 03:09

Dimitre Novatchev