1

I have an xml element:

<myElement>item1 item2 item3</myElement>

I want to use XSLT to transform it to:

<newElement>item1</newElement>  
<newElement>item2</newElement>
<newElement>item3</newElement>  

How woudl the xslt look? I am more interested in how to loop though the list of myElement or how to get it to become a list or variable.

Please advise.

3
  • Just one duplicate example in stackoverflow.com/questions/136500/… Commented Feb 7, 2011 at 17:22
  • Good question, +1. See my answer for a complete and short solution. :) Commented Feb 7, 2011 at 17:29
  • With this kind of question you need to make it clear whether you want an XSLT 1.0 or 2.0 solution. Commented Feb 7, 2011 at 18:17

2 Answers 2

2

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>


 <xsl:template match="text()[contains(., ' ')]" name="tokenize">
  <xsl:param name="pText" select="."/>

  <xsl:if test="string-length($pText)">
   <newElement>
    <xsl:value-of select=
     "substring-before(concat($pText,' '),' ')"/>
   </newElement>

   <xsl:call-template name="tokenize">
    <xsl:with-param name="pText" select=
     "substring-after($pText,' ')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<myElement>item1 item2 item3</myElement>

produces the wanted, correct result:

<newElement>item1</newElement>
<newElement>item2</newElement>
<newElement>item3</newElement>
Sign up to request clarification or add additional context in comments.

Comments

1

In XSLT 2.0 it's easier:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="myElement">
   <xsl:for-each select="tokenize(., '\s+')">
     <newElement><xsl:value-of select="."/></newElement>
   </xsl:for-each>
 </xsl:template>

</xsl:stylesheet>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.