Tonio Gela
Tonio Gela

Reputation: 120

Adding an attribute to every child node with xslt

Good morning, I'm trying to write an XSLT 1.0 trasformation to transform this

<foo>
  <document>
    <content name="bar1">Bar1</content>
    <content name="bar2">Bar2</content>
    <content name="bar3">Bar3</content>
     ...
  </document>
</foo>

to this

<foo>
  <document>
    <content name="bar1" set="top">Bar1</content>
    <content name="bar2" set="top">Bar2</content>
    <content name="bar3" set="top">Bar3</content>
     ...
  </document>
</foo>

so I tried this XSLT transformation

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

<foo>
  <document>
    <xsl:template match="/document/*">
      <xsl:copy>
        <xsl:apply-templates />
        <xsl:attribute name="set" select="'top'" />
      </xsl:copy>
    </xsl:template>
 </document>
</foo>

but sadly it didn't worked

I've tried searching a lot in xpath and xslt guides but I can't get this work, can someone help me?

Upvotes: 0

Views: 434

Answers (1)

Dan Field
Dan Field

Reputation: 21651

Your XSLT syntax is off. There are many ways to do this, here's one fairly generic way:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="content">
    <xsl:copy>
      <xsl:copy-of select="@*" />
      <xsl:attribute name="set">top</xsl:attribute>
      <xsl:value-of select="." />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

The first template is an identity template; the second template matches content nodes, copies them, their attributes, and adds the attribute set="top" and the content of the element.

Upvotes: 1

Related Questions