Is it possible to separate a number/alpha text string into two XML elements in XSLT 1.0?
My input XML is:
<root>
<tocsectionnumber>1Funding and investing</tocsectionnumber>
<tocsectionnumber>2Rules and articles</tocsectionnumber>
<tocsectionnumber>3Summary and conclusion</tocsectionnumber>
</root>
I would like my output to be:
<TocItem>
<TocItemNumber>1</TocItemNumber>
<TocItemTitle>Funding and investing</TocItemTitle>
</TocItem>
<TocItem>
<TocItemNumber>2</TocItemNumber>
<TocItemTitle>Rules and articles</TocItemTitle>
</TocItem>
<TocItem>
<TocItemNumber>3</TocItemNumber>
<TocItemTitle>Summary and conclusion</TocItemTitle>
</TocItem>
My number string could be any 1-3 digit number and the alpha string is a heading/title.
Any guidance is much appreciated.
Thanks.
You'd have to use a recursive template to count the leading digits, eg
<xsl:template name="leadingDigits">
<xsl:param name="text" select="." />
<xsl:param name="count" select="0" />
<xsl:choose>
<!-- check if the first character is a digit - when converted to number, any
digit will equal itself, any non-digit will be NaN which does _not_
equal itself -->
<xsl:when test="number(substring($text, 1, 1)) =
number(substring($text, 1, 1))">
<xsl:call-template name="leadingDigits">
<xsl:with-param name="text" select="substring($text, 2)" />
<xsl:with-param name="count" select="$count + 1" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$count" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Now you can use that to separate the string into two parts
<xsl:template match="tocsectionnumber">
<xsl:variable name="numDigits">
<xsl:call-template name="leadingDigits" />
</xsl:variable>
<TocItem>
<TocItemNumber>
<xsl:value-of select="substring(., 1, $numDigits)" />
</TocItemNumber>
<TocItemTitle>
<xsl:value-of select="substring(., $numDigits + 1)" />
</TocItemTitle>
</TocItem>
</xsl:template>
[groan] Who makes up these problems?
Anyway, try it this way:
XSLT 1.0
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<root>
<xsl:for-each select="root/tocsectionnumber">
<xsl:variable name="firstChar" select="substring(translate(., '0123456789', ''), 1, 1)" />
<TocItem>
<TocItemNumber><xsl:value-of select="substring-before(., $firstChar)"/></TocItemNumber>
<TocItemTitle><xsl:value-of select="concat($firstChar, substring-after(., $firstChar))"/></TocItemTitle>
</TocItem>
</xsl:for-each>
</root>
</xsl:template>
</xsl:stylesheet>
Note that this (or any other method) is going to bomb royally if the section title legitimately begins with a digit, eg "4. 101 Ways to Amuse Your Friends and Family".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.