XSLT applied to XML doc with xmlns attribute

Jeremy Source

I'm applying an XSLT stylesheet to the following XML file:

<top xmlns="http://www.foo.com/bar">
    <elementA />
    <elementB />
    <contents>
        <contentitem>
                <id>3</id>
                <moretags1 />
                <moretags2 />
        </contentitem>
        <contentitem>
                <id>2</id>
                <moretags1 />
                <moretags2 />
        </contentitem>
        <contentitem>
                <id>1</id>
                <moretags1 />
                <moretags2 />
        </contentitem>
    </contents>
</top>

Here's my current XSLT file (performs a simple sort):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:doc="http://www.foo.com/bar">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
<!--                                                -->
 <xsl:strip-space elements="*"/>
<!--                                                -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
<!--                                                -->
  <xsl:template match="contents">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates select="contentitem">
        <xsl:sort select="id" data-type="number"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Problem is, I do not know exactly how to use the 'doc:' namespace prefix with the xsl:template and xsl:apply-templates tags.

Right now, the XML document is copied as-is, so I believe the first xsl:template block is being applied. However, the items are unsorted, so I think the problem lies in the second xsl:template.

I should note that if I remove the xmlns attributes from both files, the transformation works properly.

Any suggestions?

(question is based on this example)

xmlsortingxsltxml-namespaces

Answers

answered 9 years ago Olivier 'Ölbaum' Scherler #1

Have you tried prefixing element names with the doc: namespace prefix in your select attributes?

<xsl:template match="doc:contents">
  <xsl:copy>
    <xsl:apply-templates select="@*"/>
    <xsl:apply-templates select="doc:contentitem">
      <xsl:sort select="doc:id" data-type="number"/>
    </xsl:apply-templates>
  </xsl:copy>
</xsl:template>

comments powered by Disqus