0

I have a variable in my xslt that looks like this.

<xsl:variable name="metadata">
    <Metadata>
        <xsl:apply-templates select="..." />
    </Metadata>
</xsl:variable>

Afterwards, I'm trying to add the metadata xml as an xsl:attribute to another node. I tried value-of, copy-of and it didn't work. When using copy-of, I got the error below.

<OtherNode>
    <xsl:attribute name="someAttr">
        <!-- I tried these and neither worked -->
        <xsl:value-of select="$metadata" /> <!-- Empty -->
        <xsl:copy-of  select="$metadata" /> <!-- Error -->
    </xsl:attribute>
</OtherNode>

An item of type 'Element' cannot be constructed within a node of type 'Attribute'.

That's fairly straight forward, but for some reason, I thought it would automatically escape the element.

I'm using xslt 1.0 by the way.

Any ideas?

Thanks

fbhdev
  • 526
  • 7
  • 17
  • fahed, You may find this answer useful -- it shows how to serialize *any* XML document as an attribute: http://stackoverflow.com/a/11623265/36305 – Dimitre Novatchev Sep 22 '12 at 02:33

2 Answers2

0

The first attempt, using value-of, should work with a little mod (using xs:text), but should have returned at least the value of the apply-templates call without the Metadata element. Are you sure the apply-templates select="..." bit is actually finding and returning something?

This works:

<xsl:variable name="metadata">
<xsl:text>&lt;Metadata></xsl:text>
    test
 <xsl:text>&lt;/Metadata></xsl:text>
</xsl:variable>


<xsl:template match="some-element">
  <xsl:element name="some-element">
    <xsl:attribute name="test"><xsl:value-of select="$metadata" /></xsl:attribute>
  </xsl:element>
</xsl:template>

and the output looks like:

 <some-element test="&lt;Metadata&gt;&#xA;        test&#xA;&lt;/Metadata&gt;">
Jayson Lorenzen
  • 575
  • 2
  • 7
  • yeah, that's what I ended up doing before I saw your answer. I was hoping I didn't need to do it this way, but oh well. Thanks! – fbhdev Sep 21 '12 at 15:33
  • No prob, definitely not a "cool" solution, but sometimes just getting it done is best. Get it done, then move on to the next problem/challenge on the project :) – Jayson Lorenzen Sep 21 '12 at 17:51
0

It seems that you have captured more than just text in your variable, but instead have node()or node-set. You need to change your variable to select just the text() that you are looking for.

StuartLC
  • 104,537
  • 17
  • 209
  • 285