user3895759
user3895759

Reputation: 31

XSL add new attribute at last position

I would like to modify an xml tree by xslt:

Add an attribute to a node, but the new attribute should be the lattest one.

Example:

<A>
   <B att1="val1" />
</A>

Result:

<A>
  <B att1="val" newAtt="newValue"/>
</A>

By using the following xsl, the attribute newAtt will be placed as first attribute of B.

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

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

Upvotes: 0

Views: 384

Answers (2)

Michael Kay
Michael Kay

Reputation: 163352

As Martin says, attributes are intrinsically unordered. Though some XSLT processors will retain the order in which attributes are written, you can't rely on this.

Saxon has an option to control the order in which attributes are serialized: see

http://www.saxonica.com/documentation/index.html#!extensions/output-extras/attribute-order

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167581

Well attributes have no order so there is no ensured ordering but you could try

<xsl:template match="B">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="newAtt">newValue</xsl:attribute>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

with your XSLT processor.

Upvotes: 1

Related Questions