XSLT 1.0需求:移除无有效addresses子节点的customer元素
解决XSLT 1.0移除无有效addresses的customer元素问题
输入XML
<response> <customers> <customer> <id>001</id> <addresses> <address> <id>a01</id> <street/> </address> <address> <id>a02</id> <street/> </address> </addresses> </customer> <customer> <id>002</id> <addresses/> </customer> </customers> </response>
期望输出
<response> <customers> <customer> <id>001</id> <addresses> <address> <id>a01</id> <street/> </address> <address> <id>a02</id> <street/> </address> </addresses> </customer> </customers> </response>
原XSLT代码问题
你使用的XSLT匹配条件逻辑偏差,无法正确识别需移除的customer节点:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:template match="customer[not(descendant::address[not(*)][normalize-space()])]"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
修正后的XSLT代码
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <!-- 移除无addresses或addresses为空的customer节点 --> <xsl:template match="customer[not(addresses) or not(addresses/node())]"/> <!-- 身份模板:复制所有未被特殊匹配覆盖的节点 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
代码说明
- 核心匹配条件
customer[not(addresses) or not(addresses/node())]:not(addresses):匹配不存在addresses子节点的customernot(addresses/node()):匹配存在addresses子节点但该节点无任何内容(空标签)的customer
- 身份模板负责保留所有未被移除逻辑命中的节点,保证XML原有结构正常复制。
内容的提问来源于stack exchange,提问作者James Taylor
相关产品推荐
相关产品推荐

