如何使用XSLT根据XML中指定元素值实现对应节点的n次复制?
调整后的XSLT代码
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"> <xsl:output indent="yes" encoding="utf-8"/> <xsl:strip-space elements="*"/> <!-- 身份复制模板:无特殊处理的节点直接原样保留 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 处理行节点,按copies数值复制对应次数 --> <xsl:template match="lines/line"> <xsl:variable name="currentLine" select="."/> <xsl:variable name="copyNum" select="xs:integer(copies)"/> <xsl:for-each select="1 to $copyNum"> <line> <!-- 复制除copies外的所有属性和子节点 --> <xsl:apply-templates select="$currentLine/@* | $currentLine/node()[not(self::copies)]"/> </line> </xsl:for-each> </xsl:template> </xsl:stylesheet>
调整说明
- 原代码错误匹配了
copies节点,同时定义了空的line匹配模板,导致原行节点被直接丢弃 - 新增的
lines/line匹配模板会读取当前行的copies数值,循环对应次数生成新的行节点 - 生成新行节点时主动过滤了copies元素,完全符合输出要求
- 保留身份复制模板,header等其余节点会原样输出,无需额外处理
内容的提问来源于stack exchange,提问作者Richard de Hond
相关产品推荐
相关产品推荐

