请求编写XSLT 1.0代码实现指定XML节点迁移需求
实现需求的XSLT 1.0代码
输入XML示例
<root> <b> <b2>8R</b2> <some>content</some> </b> <b> <b2>7S</b2> <other>stuff</other> </b> <c>c1</c> <c>c2</c> <d> <text>d1 content</text> </d> <e>e1</e> <f>f1</f> <d> <text>d2 content</text> </d> <e>e2</e> </root>
期望输出XML示例
<root> <b> <b2>8R</b2> <some>content</some> <c>c1</c> <c>c2</c> </b> <b> <b2>7S</b2> <other>stuff</other> </b> <d> <text>d1 content</text> <e>e1</e> <f>f1</f> </d> <d> <text>d2 content</text> <e>e2</e> </d> </root>
XSLT 1.0 实现代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 复制所有未被特殊模板匹配的节点和属性,保留原有基础结构 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 重新组织root节点的子节点输出顺序 --> <xsl:template match="root"> <xsl:copy> <!-- 先处理所有b节点 --> <xsl:apply-templates select="b"/> <!-- 再处理所有d节点 --> <xsl:apply-templates select="d"/> <!-- 原位置的c、e、f节点不再保留,已迁移到目标位置 --> </xsl:copy> </xsl:template> <!-- 处理b节点:仅当b2值为"8R"时,追加所有c节点 --> <xsl:template match="b"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <xsl:if test="b2 = '8R'"> <xsl:apply-templates select="/root/c"/> </xsl:if> </xsl:copy> </xsl:template> <!-- 处理d节点:将对应位置的e、f节点迁移进来 --> <xsl:template match="d"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <!-- 选取当前d节点之后、下一个d节点之前的所有e和f节点 --> <xsl:apply-templates select="following-sibling::*[self::e or self::f][not(following-sibling::d)]"/> <xsl:apply-templates select="following-sibling::*[self::e or self::f][following-sibling::d][generate-id(following-sibling::d[1]) = generate-id(current()/following-sibling::d[1])]"/> </xsl:copy> </xsl:template> <!-- 阻止原位置的c、e、f节点被重复输出 --> <xsl:template match="c|e|f"/> </xsl:stylesheet>
关键逻辑说明
- 默认模板:兜底复制所有没被特殊规则匹配的节点和属性,保证原有结构的基础完整性。
- root节点处理:重新规划输出顺序,先输出b节点,再输出d节点,跳过原位置的c、e、f节点,避免重复。
- b节点规则:匹配每个b节点,只有当内部的
<b2>值为8R时,才把根节点下所有<c>节点追加到该b节点内部。 - d节点规则:通过
following-sibling轴定位当前d节点之后、下一个d节点之前的所有<e>和<f>节点,将它们迁移到当前d节点内部,实现对应关联。 - 抑制重复输出:专门匹配
<c>、<e>、<f>的空模板,确保这些节点只在迁移后的位置出现。
内容的提问来源于stack exchange,提问作者user22788171
相关产品推荐
相关产品推荐

