Reputation: 1431
I would need to transform the response from a Solr server into an XML-like formatting by using stylesheet transformations. A number of fields from the Solr schema are multivalued and include square brackets, which indicate an array. For display purposes, I would like to remove these brackets at the beginning and the end of the field value. Currently, my XSLT looks like this (the example refers to the field title and handles records with no title, too:
<pnx:title>
<xsl:variable name="title">
<xsl:choose>
<xsl:when test="string-length(field[@name='title']) > 0">
<xsl:value-of select="field[@name='title']" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="field[@name='text']" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<!-- handle empty title -->
<xsl:choose>
<xsl:when test="string-length($title) = 0">
Untitled
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$title"/>
</xsl:otherwise>
</xsl:choose>
</pnx:title>
I would normally use substring(string, number, number) to remove characters from a string, but in this case I do not know the position of the last character. Any idea?
Thanks, I.
Upvotes: 3
Views: 16638
Reputation: 1431
I have succesfully solved the issue by using substring-before
and substring-after
. Please see below:
<pnx:title>
<xsl:variable name="title">
<xsl:choose>
<xsl:when test="string-length(field[@name='title']) > 0">
<xsl:value-of select="substring-before(substring-after(field[@name='title'],'['),']')" />
<xsl:otherwise>
<xsl:value-of select="field[@name='text']" />
</xsl:otherwise>
</xsl:when>
</xsl:choose>
</xsl:variable>
<!--handle empty title-->
<xsl:choose>
<xsl:when test="string-length($title) = 0">
Untitled
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$title"/>
</xsl:otherwise>
</xsl:choose>
</pnx:title>
Thanks,
I.
Upvotes: 1
Reputation: 3138
For example:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:variable name="abc">[11sdf sdsdf sdfds fsdf dsfsdf fsd2]</xsl:variable>
<xsl:variable name="length" select="string-length($abc)"/>
<xsl:message><xsl:value-of select=" $length"/></xsl:message>
<xsl:value-of select="substring($abc,2,($length - 2))"/>
</xsl:template>
</xsl:stylesheet>
produce output:
11sdf sdsdf sdfds fsdf dsfsdf fsd2
Upvotes: 6