Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the first and the last character of a string using XSLT

Tags:

regex

xml

solr

xslt

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']) &gt; 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.

like image 795
paranzana Avatar asked Sep 13 '26 19:09

paranzana


1 Answers

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
like image 168
Navin Rawat Avatar answered Sep 16 '26 08:09

Navin Rawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!