XSLT通配符匹配时如何排除当前节点自身以避免重复值误判
问题原因
你原来的判断逻辑Identifier/text() = //Identifier/text()会把当前Child节点下的Identifier也纳入匹配范围,所以只要当前节点有Identifier字段,这个条件就永远成立,自然一直输出create_duplicate。
解决方案
调整重复判断的条件,使用generate-id()函数排除当前节点自身的Identifier,只匹配其他Child节点下的同名字段:
把原来的
<xsl:when test="Identifier/text() = //Identifier/text()">
修改为
<!-- 仅统计除当前节点外的其他Child/Identifier是否有重复值 --> <xsl:when test="count(//Child/Identifier[text() = current()/Identifier/text() and generate-id(.) != generate-id(current()/Identifier)]) > 0">
完整修改后的XSLT代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:strip-space elements="*"/> <xsl:output indent="yes"></xsl:output> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="Child"> <xsl:copy> <xsl:apply-templates select="@* | node()"></xsl:apply-templates> <operation> <xsl:choose> <!-- 修改后的重复判断逻辑,排除当前节点自身 --> <xsl:when test="count(//Child/Identifier[text() = current()/Identifier/text() and generate-id(.) != generate-id(current()/Identifier)]) > 0"> <xsl:value-of select="'create_duplicate'"/> </xsl:when> <xsl:otherwise> <xsl:choose> <xsl:when test="Identifier/text() = //WebIdentifier/text()"> <xsl:value-of select="'update'"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="'create'"/> </xsl:otherwise> </xsl:choose> </xsl:otherwise> </xsl:choose> </operation> </xsl:copy> </xsl:template> </xsl:stylesheet>
运行结果
<Document> <List> <Child> <Identifier>19961202</Identifier> <operation>update</operation> </Child> <Child> <Identifier>19961203</Identifier> <operation>update</operation> </Child> </List> <WebResponse> <Product> <WebIdentifier>19961202</WebIdentifier> </Product> <Product> <WebIdentifier>19961203</WebIdentifier> </Product> </WebResponse> </Document>
如果你的场景中需要匹配所有Identifier而非仅Child下的,把条件里的//Child/Identifier改回//Identifier即可,核心的排除当前节点的逻辑保持不变。
内容的提问来源于stack exchange,提问作者Moontego
相关产品推荐
相关产品推荐

