Chandu
Chandu

Reputation: 2049

What is the XPath expression to select a Processing instruction?

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

Upvotes: 12

Views: 13742

Answers (3)

dingjun
dingjun

Reputation: 94

A processing-instruction hat two parts target and data with the syntax:

<?target data?>

If you use:

<xsl:value-of select="/processing-instruction('xml-stylesheet')" />

It will only return the data part, in the example of Dimitre Novatchev, it returns:

type="text/xsl" href="test"

So the string value of a processing instruction is the data part. select expression of <xsl:value-ofis evaluated and the resulting object is converted to a string, like a implicit call to the string() function.

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

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"?>

Upvotes: 11

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use processing-instruction() node-test.

Upvotes: 9

Related Questions