Henrik
Henrik

Reputation: 345

XSLT for-each counter - how to access data

for performance testing purposes I want to take a small XML file and create a bigger one from it - using XSLT. Here I plan to take each entity (Campaign node in the example below) in the original XML and copy it n times, just changing its ID. The only way I can think of to realize this, is a xsl:for-each select "1 to n". But when I do this I do not seem to be able to access the entity node anymore (xsl:for-each select="campaigns/campaign" does not work in my case). I am getting a processor error: "cannot be used here: the context item is an atomic value". It seems that by using the "1 to n" loop, I am loosing the access to my actual entity. Is there any XPath expression that gets me access back or does anyone have a completely different idea how to realize this?

Here is what I do:

Original XML

<campaigns>    
<campaign id="1" name="test">
<campaign id="2" name="another name">
</cmpaigns>

XSLT I try to use

<xsl:template match="/">
 <xsl:element name="campaigns">
 <xsl:for-each select="1 to 10">
  <xsl:for-each select="campaigns/campaign">
   <xsl:element name="campaign">
   <xsl:copy-of select="@*[local-name() != 'id']" />
   <xsl:attribute name="id"><xsl:value-of select="@id" /></xsl:attribute>
   </xsl:element>
  </xsl:for-each>
 </xsl:for-each>
 </xsl:element>
</xsl:template>

Upvotes: 1

Views: 1065

Answers (1)

hroptatyr
hroptatyr

Reputation: 4829

Define a variable as the first thing in the match, like so:

<xsl:variable name="foo" select="."/>

This defines a variable $foo of type nodeset. Then access it like this

<xsl:for-each select="$foo/campaigns/campaign">
...
</xsl:for-each>

Upvotes: 2

Related Questions