Transforming Solr responses using XSLT

I have recently been working with a SolrJ-based Java client that accesses external Solr instances and I have came across an issue with multivalued Solr fields.  Multivalued fields can take more than one value, hence they can store an array of values. More simplistically, multivalued fields can be seen as regular fields with multiple values concatenated together.

In my case, the Solr schema was set up with the following configurations for the field title:

<field name="title" type="text_general" indexed="true" stored="true" <strong>multiValued="true"</strong>/>

Consequently, the XML response from Solr displayed square brackets at the beginning and at the end of each title:

<title>[some title]</title>

The initial code for transforming the Solr response extracted the value of the field title by using

<xsl:value-of select>

and the attribute

select

The Xpath expression

field[@name='title']

then selected the attribute of the original nodes with the given attribute name ‘title’ and it retains the square brackets for array values.


<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: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>
</title>

I came up with the following solution to remove the square brackets by using the XSLT functions substring-before and substring-after. They allowed me to be returned with the substring of the field title without the left and right brackets:

<title>
 <xsl:variable name="title">
 <xsl:choose>
 <xsl:when test="string-length(field[@name='title']) &gt; 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>
</title>
Advertisements

Posted on November 1, 2013, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: