tags:

views:

39

answers:

2

I have some content being pulled in from an external xml with xsl. in the xml the title is merged with the author with a backslash seperating them.

How do I seperate the title and author in xsl so I can have them with differnt tags

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

to be

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

Hope this helps! Let me know if I misinterpreted 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>
developer
Just wanted to say thanks for your help. Smashing!!
kristina
Thanks! I'm glad it helped. If you feel it is the correct solution.. I wouldn't mind having my first *accepted* solution ;)
developer
+1  A: 

This transformation:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
    <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 on the provided XML document:

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

produces the wanted result:

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

Do note that no explicit conditional code is used -- the XSLT processor does this work itself.

Dimitre Novatchev
+1 for doing it just with template matches.
Zachary Young