Reputation: 277
I have a very simple query, but not able to find the easiest/elegant way to solve it. If my input XML has a tag with string content "YY nnn" where YY is alphanumeric 2 characters, followed by a space, and then upto 4 numerics. In my output XML I need to strip the space if the numerics are 4 characters - ie. "YY nnnn" and retain the space if "YY nnn". I have tried with a string length check and then strip the space, but I'm sure there must be a simpler way.
Any ideas?
I am using xlstproc on linux for the transforms.
Thanks!
Upvotes: 1
Views: 504
Reputation: 12154
Sample Input XML:
<?xml version="1.0" encoding="utf-8"?>
<root>
<MyNode>AZ 1234</MyNode>
<MyNode>A3 123</MyNode>
<MyNode>7Z 12345</MyNode>
<MyNode>15 23</MyNode>
</root>
XSLT code:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="MyNode">
<xsl:copy>
<xsl:choose>
<xsl:when test="string-length(substring-after(.,' '))='4'">
<xsl:value-of select="concat(substring-before(.,' '), substring-after(.,' '))"/>
</xsl:when>
<xsl:when test="string-length(substring-after(.,' '))='3'">
<xsl:value-of select="."/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Output:
<?xml version="1.0" encoding="utf-8"?>
<root>
<MyNode>AZ1234</MyNode>
<MyNode>A3 123</MyNode>
<MyNode>7Z 12345</MyNode>
<MyNode>15 23</MyNode>
</root>
Upvotes: 1