Jaroslav Bačkora
Jaroslav Bačkora

Reputation: 79

XSLT add attributes to elements in a variable

In XSLT 1.0 I have a variable with some XML nodes:

<xsl:varible name="MyVariable">
   <SomeElement>text here</SomeElement>
   <SomeElement>text with <OtherElement>other element</OtherElement></SomeElement>
   <SomeElement>something else <DoNotAddAnything>...</DoNotAddAnything></SomeElement>
</xsl:variable>

I need to add an attribute with some value to elements SomeElement and OtherElement (but not to others). I need to transform the content of the variable to something like this:

   <SomeElement NewAttribute="x">text here</SomeElement>
   <SomeElement NewAttribute="x">text with <OtherElement OtherAttribute="y">other element</OtherElement></SomeElement>
   <SomeElement NewAttribute="x">something else <DoNotAddAnything>...</DoNotAddAnything></SomeElement>

This is part of larger transformation, and I only need to do this for the content of the variable, not for the entire input of XSLT transformation. I found easy solutions for converting entire input (xsl:apply-template) but I'm having hard times to achieve the same only for the content of a variable. Thanks a lot.

Upvotes: 1

Views: 2404

Answers (1)

Tomalak
Tomalak

Reputation: 338406

In XSLT 1.0 I have a variable with some XML nodes:

That's a misconception. You have a variable with a result tree fragment, which is strictly not the same as "some XML nodes".

You must convert the result tree fragment back to actual XML nodes. With vanilla XSLT 1.0 this is not possible, but many XSLT processors have an extension function called node-set() that does just that. How to enable that function depends on your specific XSLT processor.

<xsl:apply-templates select="exslt:node-set($MyVariable)" />

and

<xsl:template match="SomeElement">
  <xsl:copy>
    <xsl:copy-of select="@*" />
    <xsl:attribute name="NewAttribute">x</xsl:attribute>
    <xsl:copy-of select="node()" />
  <xsl:copy>
</xsl:template>

That said, it strikes me as odd that you're trying to use a variable with "some XML nodes" in it. Except for very special cases you should not have to do that, so I think you might be doing something wrong.


Note that

<xsl:variable name="foo" select="/some/xml/nodes" />

does not contain a result tree fragment, but an ordinary node set.

However, a variable that is not defined via select="..." never contains actual nodes, but always result tree fragments (which you can think about as strings, basically).

Upvotes: 1

Related Questions