XSLT使用AND组合多when条件判断双节点值未返回预期结果问题
问题描述
需求是通过AND组合的XSLT when条件同时校验两个XML节点的值,两个条件同时满足时输出对应文本。
- 测试XML文件1:
<mxc> <einvoice> <buyer> <endpoint>36433875185</endpoint> <registeredname>LAV</registeredname> </buyer> </einvoice> </mxc>
- 测试XML文件2:
<mxc> <einvoice> <buyer> <endpoint>36433875185</endpoint> <registeredname></registeredname> </buyer> </einvoice> </mxc>
编写的XSLT代码运行后始终输出WRONG,预期效果为匹配XML文件1时返回1310、匹配XML文件2时返回1170,原错误代码如下:
<xsl:output method="text" /> <xsl:template match="/"> <xsl:choose> <xsl:when test="mxc/einvoice/buyer/registeredname=LAV and mxc/einvoice/buyer/endpoint=36433875185"> <xsl:text>1310</xsl:text> </xsl:when> <xsl:when test="mxc/einvoice/buyer/registeredname=' ' and mxc/einvoice/buyer/endpoint=36433875185"> <xsl:text>1170</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>WRONG</xsl:text> </xsl:otherwise> </xsl:choose> </xsl:template>
错误原因
代码存在3个核心问题,导致所有判断条件均匹配失败:
- 字符串匹配未给字面量加引号:XPath语法规则中,不带引号的字符序列会被解析为节点名称,写法
registeredname=LAV实际是在判断registeredname节点值和名为LAV的子节点值是否相等,并非和字符串"LAV"做比较,第一个条件永远无法命中。 - 空节点判断值写错:XML文件2中
<registeredname></registeredname>的节点值是空字符串'',代码中写的判断值是' '(引号中间包含1个空格字符),和实际空值不匹配,第二个条件也无法命中。 - 存在类型转换隐患:endpoint节点存储的是字符串类标识号,代码中直接写
36433875185会被解析为数值类型,XSLT 1.0处理长数字时可能出现精度丢失问题,统一加引号做字符串比较更稳妥。
修正后可运行代码
<xsl:output method="text" /> <xsl:template match="/"> <xsl:choose> <xsl:when test="mxc/einvoice/buyer/registeredname='LAV' and mxc/einvoice/buyer/endpoint='36433875185'"> <xsl:text>1310</xsl:text> </xsl:when> <xsl:when test="mxc/einvoice/buyer/registeredname='' and mxc/einvoice/buyer/endpoint='36433875185'"> <xsl:text>1170</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>WRONG</xsl:text> </xsl:otherwise> </xsl:choose> </xsl:template>
内容的提问来源于stack exchange,提问作者Jana
相关产品推荐
相关产品推荐

