XSLT技术问题:提取文本子串转整数时出现NaN转换错误
提取XML标题中的循环数字并转换为整数的问题解决
原始XML内容
<p outputclass="Heading">Cycles 1–5</p> <p outputclass="Heading">Cycles 6–10</p> <p outputclass="Heading">Cycles 11–16</p>
错误的XSLT代码
<xsl:for-each select="p[@outputclass = 'Heading' and starts-with(., 'Cycles ')]"> <xsl:variable name="cycle_begin_string" select="substring-after(.,'Cycles ') and substring-before(.,'–')"/> <xsl:variable name="cycle_end_string" select="substring-after(., '–')"/> <xsl:variable name="cycle_begin_number" select="number($cycle_begin_string)"/> <xsl:variable name="cycle_end_number" select="number($cycle_end_string)"/> <xsl:variable name="cycle_begin_integer" select="xs:integer($cycle_begin_number)"/> <xsl:variable name="cycle_end_integer" select="xs:integer($cycle_end_number)"/> </xsl:for-each>
错误原因分析
cycle_begin_string变量逻辑错误:你用and逻辑运算符连接两个字符串函数,这会返回布尔值(true/false)而非目标字符串。正确操作是嵌套调用字符串函数:先通过substring-after获取Cycles之后的内容,再用substring-before从该结果中提取破折号–前的数字字符串。- 破折号匹配需注意:确保XSLT代码中的破折号
–与XML中的完全一致(此处为英文短破折号),避免因字符不匹配导致提取失败。
修正后的XSLT代码
<xsl:for-each select="p[@outputclass = 'Heading' and starts-with(., 'Cycles ')]"> <!-- 正确提取起始循环的数字字符串 --> <xsl:variable name="cycle_begin_string" select="substring-before(substring-after(., 'Cycles '), '–')"/> <!-- 提取结束循环的数字字符串 --> <xsl:variable name="cycle_end_string" select="substring-after(., '–')"/> <!-- 直接将合法数字字符串转换为整数,无需先转number类型 --> <xsl:variable name="cycle_begin_integer" select="xs:integer($cycle_begin_string)"/> <xsl:variable name="cycle_end_integer" select="xs:integer($cycle_end_string)"/> <!-- 可选:输出验证提取结果 --> <xsl:text>起始循环:</xsl:text> <xsl:value-of select="$cycle_begin_integer"/> <xsl:text>,结束循环:</xsl:text> <xsl:value-of select="$cycle_end_integer"/> <xsl:text> </xsl:text> </xsl:for-each>
优化说明
xs:integer()可直接解析合法的数字字符串,无需先通过number()转换,减少不必要的步骤;添加的输出代码可直观验证提取的整数是否正确。
内容的提问来源于stack exchange,提问作者Randy H in CT
相关产品推荐
相关产品推荐

