Split string in xsl for content with /

I have content that is pulled from external xml with xsl. In xml, the title is combined with the author with a backslash separating them.

How to separate title and author in xsl so that I can have them with different tags

<product>
  <title>The Maze / Jane Evans</title> 
</product>

to be

<h2>The Maze</h2>
<p>Jane Evans</p>
+3
source share
3 answers

Hope this helps! Let me know if I misunderstood the question!

<xsl:variable name="title">
    <xsl:value-of select="/product/title"/>
</xsl:variable>

<xsl:template match="/">
    <xsl:choose>
        <!--create new elements from existing text-->
        <xsl:when test="contains($title, '/')">
            <xsl:element name="h2">
                <xsl:value-of select="substring-before($title, '/')"/>
            </xsl:element>
            <xsl:element name="p">
                <xsl:value-of select="substring-after($title, '/')"/>
            </xsl:element>
        </xsl:when>
        <xsl:otherwise>
            <!--no '/' deliminator exists-->
            <xsl:value-of select="$title"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
+1
source

This conversion is :

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

 <xsl:template match="title[contains(., '/')]">
   <h2>
    <xsl:value-of select="substring-before(., '/')"/>
   </h2>
   <p>
    <xsl:value-of select="substring-after(., '/')"/>
   </p>
 </xsl:template>

 <xsl:template match="title">
   <h2><xsl:value-of select="."/></h2>
 </xsl:template>
</xsl:stylesheet>

when applied to the provided XML document :

<product>
  <title>The Maze / Jane Evans</title>
</product>

creates the desired result :

<h2>The Maze </h2>
<p> Jane Evans</p>

Note that explicit conditional code is not used - the XSLT processor does this work itself.

+1
0

Source: https://habr.com/ru/post/1750158/


All Articles