如何优化XSLT以处理名称不同但内容一致的嵌套XML节点
XSLT优化方案
核心思路
利用XSLT的模板匹配能力,针对三类结构一致的节点编写唯一通用模板,嵌套逻辑通过层级自动触发,完全覆盖所有6种场景,无重复代码。
具体实现代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <!-- 根节点处理 --> <xsl:template match="/item/itemdetail"> <Products> <!-- 优先处理parentitem,不存在则直接处理childitem --> <xsl:choose> <xsl:when test="parentitem"> <xsl:apply-templates select="parentitem"/> </xsl:when> <xsl:when test="childitem"> <xsl:apply-templates select="childitem"/> </xsl:when> <!-- parent和child都不存在时直接处理subchild --> <xsl:otherwise> <xsl:apply-templates select="subchildren/subchild"/> </xsl:otherwise> </xsl:choose> </Products> </xsl:template> <!-- 通用模板:匹配三类结构一致的节点 --> <xsl:template match="parentitem | childitem | subchild"> <Product type="{name()}"> <!-- 直接拷贝当前节点下所有子字段,不用逐个硬编码 --> <xsl:copy-of select="*"/> <!-- 嵌套下一层节点:parent下嵌套child --> <xsl:if test="self::parentitem and ../childitem"> <xsl:apply-templates select="../childitem"/> </xsl:if> <!-- 嵌套下一层节点:child下嵌套subchild --> <xsl:if test="self::childitem and ../subchildren/subchild"> <xsl:apply-templates select="../subchildren/subchild"/> </xsl:if> </Product> </xsl:template> </xsl:stylesheet>
方案说明
- 通用模板仅写1次,自动适配
parentitem/childitem/subchild三类节点的字段输出,完全消除重复的字段处理代码 - 嵌套逻辑通过节点类型判断自动触发,无需为6种场景单独编写硬编码逻辑,节点不存在时自动跳过对应层级
- 可扩展性强:如果后续新增其他层级节点,只需在通用模板的匹配规则和嵌套判断中增加对应节点名即可,无需修改现有逻辑
- 输出结果完全符合要求的嵌套规则,与示例输出完全一致
内容的提问来源于stack exchange,提问作者Spacko
相关产品推荐
相关产品推荐

