tags:

views:

44

answers:

2

I have the following fragment in XSLT. Is there a way to rewrite it without escaping the characters < and > with the ASCII equivalent?

<coord>
...
<xsl:with-param name="substringIn" select="'' ''"/>
<xsl:with-param 
  name="substringOut" 
  select="'&#60;/coord&#62;&#60;coord&#62;'" 
/> 
...
</coord>

I have a string of space delimited numbers like

<value>1 2 3 4 5 6 7</value> 

and I would like to convert each one of them in XML tags like:

<coord>1</coord>
<coord>2</coord>
<coord>3</coord>
<coord>4</coord>
<coord>5</coord>
<coord>6</coord>
<coord>7</coord>

My code above does that, but I don't want to use the ASCII escape chars.

+4  A: 

The XSLT way of splitting a string and wrapping the constituents in elements is this:

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

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>

  <xsl:choose>
   <xsl:when test="not(contains($pText, ' '))">
    <coord><xsl:value-of select="$pText"/></coord>
   </xsl:when>
   <xsl:otherwise>
    <coord>
     <xsl:value-of select="substring-before($pText, ' ')"/>
    </coord>

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

when this transformation is applied on this XML document:

<t>1 2 3 4 5 6 7</t>

the wanted, correct result is produced:

<coord>1</coord>
<coord>2</coord>
<coord>3</coord>
<coord>4</coord>
<coord>5</coord>
<coord>6</coord>
<coord>7</coord>
Dimitre Novatchev
@Dimitre: +1 Good solution. But I think that normalizing default param value adding a space will make posible a compact code with just one `xls:if`.
Alejandro
@Alejandro: Yes, but in a realworld case only rarely is a single space the only delimiter -- my solution works in all cases, while a `normalize-space()` solution works only in the case of a space-delimiter.
Dimitre Novatchev
A: 

You can use a CDATA section:

<xsl:with-param name="substringOut"><![CDATA[</coord><coord>]]></xsl:with-param>
dolmen