Svish
Svish

Reputation: 158051

Match a node without namespace in XSLT

Given the following XSLT:

<stylesheet version="2.0" 
    xmlns="http://www.w3.org/1999/XSL/Transform"
    xmlns:cm="http://api.example.com/schema">

    <template match="?">
        <element name="cm:Foo"><value-of select="?" /></element>
    </template>

</stylesheet>

And this XML:

<a>
  <b>cat</b>
</a>

How do I match the a node and select the value of the b node?

Notice that they do not have any namespace, and the default namespace in the stylesheet is already used, so simply match="a" and select="b" won't work (as far as I can see).

Upvotes: 1

Views: 2921

Answers (3)

Svish
Svish

Reputation: 158051

@pgfearo posted and deleted an answer which was correct. The solution was to set xpath-default-namespace="" on the stylesheet. So working xslt would be:

<stylesheet version="2.0" 
    xmlns="http://www.w3.org/1999/XSL/Transform"
    xmlns:cm="http://api.example.com/schema"
    xpath-default-namespace="">

    <template match="a">
        <element name="cm:Foo"><value-of select="b" /></element>
    </template>

</stylesheet>

Without setting the xpath-default-namespace it doesn't match, which makes sense since there is no a or b node with the XSL Transform namespace.

Upvotes: 1

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

The default namespace of one XML document (your XSLT stylesheet) cannot influence in any way whether or not another XML document has a default namespace.

Simply use:

<xsl:template match="a">
  <xsl:value-of select="b"/>
</xsl:template>

Also, remember that XPath always treats an unprefixed name as belonging to "no namespace".

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167571

<xsl:template match="a">
  <xsl:value-of select="b"/>
</xsl:template>

should do as the default namespace in the stylesheet code does not matter for XSLT patterns and XPath expressions. So a always means an element with local name a in no namespace, unless you use XSLT 2.0 and set xpath-default-namespace="...", see http://www.w3.org/TR/xslt20/#unprefixed-qnames. Your xmlns="..." does not matter.

Upvotes: 0

Related Questions