Oleg Pavliv
Oleg Pavliv

Reputation: 21162

xsl attribute namespace

I have the following xml

<?xml version="1.0" encoding="UTF-8"?>
<content>
  <artwork classification="12" href="1.jpg"/>
  <artwork classification="10" href="2.jpg"/>
</content>

When applying the xsl

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                >

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@href">
    <xsl:attribute name="xlink:href">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

it produces

<?xml version="1.0" encoding="UTF-8"?>
<content>
  <artwork classification="12" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="1.jpg"/>
  <artwork classification="10" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="2.jpg"/>
</content>

whereas I need

<?xml version="1.0" encoding="UTF-8"?>
<content xmlns:xlink="http://www.w3.org/1999/xlink">
  <artwork classification="12"  xlink:href="1.jpg"/>
  <artwork classification="10"  xlink:href="2.jpg"/>
</content>

How should I modify my xsl to get the result I need?

I use xalan XSLT processor.

Upvotes: 2

Views: 6939

Answers (1)

Emiliano Poggi
Emiliano Poggi

Reputation: 24816

You need just to match the elements for which you want the namespace declared. The processor will apply the namespace for you.


XSLT 1.0 tested under MSXSL 4.0 (and also tested as XSLT 2.0 under Saxon-HE 9.2.1.1J)

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    >

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="content">
        <content>
            <xsl:apply-templates select="@*|node()"/>
        </content>
    </xsl:template>

    <xsl:template match="@href">
        <xsl:attribute name="xlink:href">
            <xsl:value-of select="."/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

Upvotes: 5

Related Questions