Re: [xsl] How to extract value of variable number of attributes in an XML t ag through XSL?

Subject: Re: [xsl] How to extract value of variable number of attributes in an XML t ag through XSL?
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Tue, 16 Nov 2004 16:02:14 +0000
Hi Anoop,

> If I could loop through the list of attributes in these, it could be
> easy to implement so that I could get to table tag and loop through
> its attributes list and add more attributes also. But I don't know
> how to do that. Because I don't know for sure what attributes may be
> present each time, I can't hardcode each attribute's value in final
> output. Please suggest if there could be an implementation for what
> I am trying to do.

Use the step "@*" to access all the attributes on the context node.
For example:

<xsl:template match="table">
  <table class="...">
    <xsl:copy-of select="@*" />
    <xsl:apply-templates />
  </table>
</xsl:template>

will copy all the attributes on the <table> element to the new <table>
element. Or, if you need to add defaults when the value is missing,
you can do, for example:

<xsl:template match="table">
  <table class="...">
    <xsl:apply-templates select="@*" mode="copy" />
    <xsl:apply-templates />
  </table>
</xsl:template>

<xsl:template match="@*" mode="copy">
  <xsl:attribute name="{name(.)}">
    <xsl:choose>
      <xsl:when test="string(.)">
        <xsl:value-of select="." />
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates select="." mode="default" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</xsl:template>

<xsl:template match="align" mode="default">left</xsl:template>
<xsl:template match="bgcolor" mode="default">white</xsl:template>
<xsl:template match="colspan" mode="default">1</xsl:template>
...

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/

Current Thread