Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XSL: Dynamically create id's?

Status
Not open for further replies.

MrPeds

Programmer
Jan 7, 2003
219
0
0
GB
Hi,

I have an element like the following:

<parentElement>
<childElement>blah1</childElement>
<childElement>blah2</childElement>
<childElement>blah3</childElement>
<parentElement>

I basically want to loop through each child and create a text box with an incrementing id, so i basically want in HTML

<input type=&quot;text&quot; name=&quot;child1&quot; value=&quot;blah1&quot;/>
<input type=&quot;text&quot; name=&quot;child2&quot; value=&quot;blah2&quot;/>
<input type=&quot;text&quot; name=&quot;child3&quot; value=&quot;blah3&quot;/>

I know how to use XSL attributes and to do basic formatting but am not sure how to incorporate loop variables into the inputs.

Any suggestions/links would be very useful,

Thanks,

MrPeds
 
In XML, you cannot increment local variables and re-store them (with regards to <xsl:param> and <xsl:variable> tags, anyways). They're pretty much static once they've been passed in or selected from XML. Therefore, a fairly basic for/next loop with an incrementing variable type code block in XSLT requires a slightly different approach.

In XPath, there is a function called position() which will return the nodes position number within the context of the parent node (much like a recordset cursor position in databases). You can use this to simulate an incrementing for loop variable. Here's an example:

...

<xsl:for-each select=&quot;parentElement/children&quot;>
<input type=&quot;text&quot;>
<xsl:attribute name=&quot;name&quot;>
child<xsl:value-of select=&quot;position()&quot;/>
</xsl:attribute>
...
</xsl:for-each>
...

I believe position() also works within templates, called ones or otherwise.


Hope this helps :)

Matt
 
flumpy is right: here is an XSL document that will do your translation:

Code:
<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
<xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;[URL unfurl="true"]http://www.w3.org/1999/XSL/Transform&quot;>[/URL]
 <xsl:template match=&quot;childElement&quot;>
  <input type=&quot;text&quot;>
   <xsl:attribute name=&quot;name&quot;>child<xsl:value-of select=&quot;position()&quot;/></xsl:attribute>
   <xsl:attribute name=&quot;value&quot;><xsl:value-of select=&quot;.&quot;/></xsl:attribute>
  </input>
 </xsl:template>
</xsl:stylesheet>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top