How to creating a variable containing elements?

Here should go questions about transforming XML with XSLT and FOP.
kjforsyth
Posts: 6
Joined: Tue Jan 27, 2009 12:29 am

How to creating a variable containing elements?

Post by kjforsyth »

Greetings,

I am trying to create variables that contain elements rather than text values.

I have an XML file like this:

Code: Select all

<document>
<item name='ItemRed'>
<text>item red text</text>
</item>
<item name='ItemYellow'>
<text>item yellow text</text>
</item>
<item name='ItemBlue'>
<text>item blue text</text>
</item>
<item name='ItemGreen'>
<text>item green text</text>
</item>
</document>
In my XSL sheet, I want to build 4 variables, one for each <item>. The variables might be something like this:

Code: Select all

<xsl:variable name="itemRed" select="document/item[1]"/>
<xsl:variable name="itemYellow" select="document/item[2]"/>
<xsl:variable name="itemBlue" select="document/item[3]"/>
<xsl:variable name="itemGreen" select="document/item[4]"/>
The problem is that items could be in any order, so I can't hard-code the Xpath. How can I assign each variable to its correct item, regardless of its position in the document?

I would be most grateful for a suggestion here..

Best wishes,

Karl Forsyth
george
Site Admin
Posts: 2095
Joined: Thu Jan 09, 2003 2:58 pm

Re: How to creating a variable containing elements?

Post by george »

You can identify the items by testing their name attribute. A better way (from a performance point of view) is to use a key, see below an example with both approaches:

Code: Select all


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output indent="yes"/>
<xsl:key name="itemsByName" match="item" use="@name"/>
<xsl:template match="/">
<xsl:variable name="itemRed" select="document/item[@name='ItemRed']"/>
<xsl:variable name="itemYellow" select="document/item[@name='ItemYellow']"/>
<xsl:variable name="itemBlue" select="document/item[@name='ItemBlue']"/>
<xsl:variable name="itemGreen" select="document/item[@name='ItemGreen']"/>
<result>
<xsl:copy-of select="$itemBlue"/>
<xsl:copy-of select="key('itemsByName', 'ItemBlue')"/>
</result>
</xsl:template>
</xsl:stylesheet>
Best Regards,
George
George Cristian Bina
kjforsyth
Posts: 6
Joined: Tue Jan 27, 2009 12:29 am

Re: How to creating a variable containing elements?

Post by kjforsyth »

Just what I needed. Thank you!
Post Reply