Page 1 of 1

How to creating a variable containing elements?

Posted: Wed Jan 28, 2009 11:50 pm
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

Re: How to creating a variable containing elements?

Posted: Thu Jan 29, 2009 9:19 am
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

Re: How to creating a variable containing elements?

Posted: Fri Jan 30, 2009 4:34 am
by kjforsyth
Just what I needed. Thank you!