开发者

XSLT: Regex to check for int

i need data that is only in int forma开发者_如何学Pythont

when the node value comes in and starts with 00 then i need to change the 00 to 20

so when a non int value comes in, i can skip it

good:

<node>2322</node>

skip:

<node>232dasdf2</node>

Replace:

<node>0014</node>

-->

2014


Something like this would work :

<xsl:template match="/root">
<root>
  <xsl:for-each select="//node">
    <xsl:if test=". castable as xs:integer">
      <node>
        <xsl:value-of select="replace(., '^0{2}([\d]+)$', '20$1')"/>
      </node>
    </xsl:if>
  </xsl:for-each>
</root>

EDIT : based on observations by @Michael Kay


Sorry, I don't know how to do this in XSLT but maybe this will be useful:

<?php
$data = Array("00123", "1234", "a1234sa");

foreach( $data as $d )
{
        if(preg_match("/^\d+$/", $d))
        {
                $d = preg_replace("/^(00)?(\d+)$/e", '("$1"=="00"?"20":"")."$2"', $d);
                echo "$d\n";
        }
}

HTH, Alex


You don't need true RegEx capability for this and the problem can be solved easily in pure XSLT 1.0:

<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="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match=
  "n/text()[floor(.) = . and starts-with(., '00')]">

  <xsl:value-of select="concat('2', substring(.,2))"/>
 </xsl:template>

  <xsl:template match="n[not(floor(.) = .)]"/>
</xsl:stylesheet>

When this transformation is applied on the following XML document:

<t>
 <n>2322</n>
 <n>232dasdf2</n>
 <n>0014</n>
</t>

the wanted, correct result is produced:

<t>
    <n>2322</n>
    <n>2014</n>
</t>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜