Extracting a number (+ int / decimal) from a string with XSLT 1.0

I already wrote XSLT code to extract numeric characters from a string.

This is the xml test:
(looks a little strange, but I expect a lot from XSLT)

<xml>
  <tag>10a08bOE9W234 W30D:S</tag>
  <tag>10.233.23</tag>
</xml>

This is the XSLT code I'm trying with:

<xsl:template match="tag">
  <tag>
  <xsl:value-of select="number(translate(., 'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|.|:| ', ''))"/>
<!-- I am not happy writing this line .. is there any light weight code replacement-->
  </tag>
</xsl:template>

Outputs ..

  <tag>1008923430</tag>
  <tag>1023323</tag>

..
And more than that. I want the second tag to be displayed as 10.23323, i.e. Allowing only the first decimal point .and ignoring the following.

Is this only possible with XSLT 1.0 ??

+3
source share
2 answers

The only XPath expression for the first line :

translate(., translate(.,'0123456789', ''), '')

Note that any non-numeric character (unknown in advance) will be deleted.

:

   concat(
    substring-before(
        translate(., translate(.,'.0123456789', ''), ''),
        '.'
              ),

    substring(
        translate(., translate(.,'.', ''), ''),
         1,
         1
        ),

    translate(
        substring-after(
                  translate(., translate(.,'.0123456789', ''), ''),
                  '.'
                  ),
        '.',
        ''
        )
    )

XPath:

   . 

concat (., '.0')

+5

-, , "pipe" . , .

, , -before substring-after, , .

:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="tag">
      <xsl:variable name="NumberWithDots" select="translate(., 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ: ', '')"/>
      <tag>
         <xsl:choose>
            <xsl:when test="contains($NumberWithDots, '.')">
               <xsl:value-of select="substring-before($NumberWithDots, '.')"/>
               <xsl:text>.</xsl:text>
               <xsl:value-of select="translate(substring-after($NumberWithDots, '.'), '.', '')"/>
            </xsl:when>
            <xsl:otherwise>
               <xsl:value-of select="number($NumberWithDots)"/>
            </xsl:otherwise>
         </xsl:choose>
      </tag>
   </xsl:template>
</xsl:stylesheet>
+3

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


All Articles