假设我有一个像
这样的xml<Fractions>
<Fraction>test 1/3 test aaa</Fraction>
<Fraction>1/2 test</Fraction>
</Fractions>
我想用xsl替换字符串中的1/3 with &frac13
,1/2 with @amp;frac12
,但我被卡住了。分数值受限于
1/2, 1/3, 3/4, 1/4.
答案 0 :(得分:1)
如果您可以保证输入XML只有一位数字,您可以使用简单的查找表来实现这一点,查找表返回基数(一,二,三等)或序数形式的名称数字(半数,三数,四等)
<ref:cardinals>
<ref:cardinal>One</ref:cardinal>
<ref:cardinal>Two</ref:cardinal>
<ref:cardinal>Three</ref:cardinal>
... and so on...
</ref:cardinals>
<ref:ordinals>
<ref:ordinal>Half</ref:ordinal>
<ref:ordinal>Third</ref:ordinal>
... and so on ...
</ref:ordinals>
( ref 名称空间必须在XSLT顶部声明)
要在这些查找表中查找值,您可以设置一个引用XSLT文档本身的变量
<xsl:variable name="cardinals" select="document('')/*/ref:cardinals"/>
<xsl:value-of select="$cardinals/ref:cardinal[position() = $numerator]"/>
(其中$ numerator是包含分数上半部分的变量)
这是一个完整的XSLT文档,可以处理所有单个数字分数
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ref="http://stackoverflow.com/users/723763/abdul-muqtadir">
<xsl:output method="xml" indent="yes"/>
<ref:cardinals>
<ref:cardinal>One</ref:cardinal>
<ref:cardinal>Two</ref:cardinal>
<ref:cardinal>Three</ref:cardinal>
<ref:cardinal>Four</ref:cardinal>
<ref:cardinal>Five</ref:cardinal>
<ref:cardinal>Six</ref:cardinal>
<ref:cardinal>Seven</ref:cardinal>
<ref:cardinal>Eight</ref:cardinal>
<ref:cardinal>Nine</ref:cardinal>
</ref:cardinals>
<ref:ordinals>
<ref:ordinal>Half</ref:ordinal>
<ref:ordinal>Third</ref:ordinal>
<ref:ordinal>Quarter</ref:ordinal>
<ref:ordinal>Fifth</ref:ordinal>
<ref:ordinal>Sixth</ref:ordinal>
<ref:ordinal>Seventh</ref:ordinal>
<ref:ordinal>Eigth</ref:ordinal>
<ref:ordinal>Ninth</ref:ordinal>
</ref:ordinals>
<xsl:variable name="cardinals" select="document('')/*/ref:cardinals"/>
<xsl:variable name="ordinals" select="document('')/*/ref:ordinals"/>
<xsl:template match="Fraction">
<xsl:variable name="numerator" select="number(substring-before(., '/'))"/>
<xsl:variable name="denominater" select="number(substring-after(., '/'))"/>
<xsl:copy>
<xsl:value-of select="$cardinals/ref:cardinal[position() = $numerator]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="$ordinals/ref:ordinal[position() = $denominater - 1]"/>
<xsl:if test="$numerator != 1">s</xsl:if>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
当应用于输入XML时,将返回以下XML
<Fractions>
<Fraction>One Third</Fraction>
<Fraction>One Half</Fraction>
</Fractions>
请注意,您可能需要更好地处理复数形式。例如,如果您将3/2作为分数,则上述解决方案将返回三半,而不是三半。
答案 1 :(得分:0)
如果只有少数,请使用以下模板:
<xsl:template match="Fraction/text()[.='1/2']">half</xsl:template>
<xsl:template match="Fraction/text()[.='1/3']">one-third</xsl:template>
etc..