我有这样的xml,
<doc>
<p>ABC Number 132, Decimal 321, AAB Double 983 DEF GHI 432 JKL</p>
</doc>我的目标是,如果' number ','Decimal','Double‘后面跟着一个空格(’'),后面跟着一个数字,那么这个中间空格值应该替换为*字符。
所以输出应该是,
<doc>
<p>ABC Number*132, Decimal*321, AAB Double*983 DEF GHI 432 JKL</p>
</doc>我有后续的xsl,
<xsl:template match="p">
<xsl:analyze-string select="text()" regex="(Number/s/d)|(Decimal/s/d)|(Double/s/d)">
<xsl:matching-substring>
<xsl:choose>
<xsl:when test="regex-group(1)">
<xsl:value-of select="'Number*'"/>
</xsl:when>
<xsl:when test="regex-group(2)">
<xsl:value-of select="'Decimal*'"/>
</xsl:when>
<xsl:when test="regex-group(3)">
<xsl:value-of select="'Double*'"/>
</xsl:when>
</xsl:choose>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>但是它没有返回正确的结果。
有什么建议吗?如何修改我的代码以获得正确的输出?
发布于 2016-04-30 03:46:09
正则表达式中的主要问题是,您正在尝试将空间和数字与/s和/d匹配。
应该是\s和\d。
然而,即使你修复了这个问题,你仍然会失去数字,因为你没有捕捉它。
您还会丢失p元素。
我建议使用一个简单的正则表达式,并添加xsl:copy以保留p.
XSLT2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p">
<xsl:copy>
<xsl:analyze-string select="." regex="(Number|Decimal|Double)\s(\d)">
<xsl:matching-substring>
<xsl:value-of select="concat(regex-group(1),'*',regex-group(2))"/>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>输出
<doc>
<p>ABC Number*132, Decimal*321, AAB Double*983 DEF GHI 432 JKL</p>
</doc>发布于 2016-05-01 18:20:56
更简单更短的
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p/text()">
<xsl:value-of select="replace(., '(Number|Decimal|Double) (\d+)', '$1*$2')"/>
</xsl:template>
</xsl:stylesheet>https://stackoverflow.com/questions/36950000
复制相似问题