如何在XSLT中重命名多个不同名称的元素?
XSLT批量重命名XML元素实现方案
输入XML
<B> <A> <Year>9</Year> <Age>40</Age> <Value>32923.38</Value> <Value1>135223</Value1> <Value2>35</Value2> <Value3>114</Value3> </A> <A> <Year>19</Year> <Age>30</Age> <Value>42578.40</Value> <Value1>123</Value1> <Value2>70</Value2> <Value3>115</Value3> </A> </B>
期望输出XML
<c> <A> <day>9</day> <type>40</type> <key>32923.38</key> <level>135223</level> <pay>35</pay> <terms>114</terms> </A> <A> <day>19</day> <type>30</type> <key>42578.40</key> <level>123</level> <pay>70</pay> <terms>115</terms> </A> </c>
已尝试的XSLT模板
<xsl:template match="B/A"> <C><xsl:apply-templates select="@*|node()" /></C> </xsl:template>
解决方案XSLT代码
<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> <!-- 重命名根元素B为c --> <xsl:template match="B"> <c> <xsl:apply-templates select="@*|node()"/> </c> </xsl:template> <!-- 重命名Year为day --> <xsl:template match="Year"> <day> <xsl:apply-templates select="@*|node()"/> </day> </xsl:template> <!-- 重命名Age为type --> <xsl:template match="Age"> <type> <xsl:apply-templates select="@*|node()"/> </type> </xsl:template> <!-- 重命名Value为key --> <xsl:template match="Value"> <key> <xsl:apply-templates select="@*|node()"/> </key> </xsl:template> <!-- 重命名Value1为level --> <xsl:template match="Value1"> <level> <xsl:apply-templates select="@*|node()"/> </level> </xsl:template> <!-- 重命名Value2为pay --> <xsl:template match="Value2"> <pay> <xsl:apply-templates select="@*|node()"/> </pay> </xsl:template> <!-- 重命名Value3为terms --> <xsl:template match="Value3"> <terms> <xsl:apply-templates select="@*|node()"/> </terms> </xsl:template> </xsl:stylesheet>
代码说明
- 默认复制模板确保所有未单独匹配的节点(如
<A>)会被原样保留,维持原有结构和内容。 - 针对根元素
<B>单独编写匹配模板,替换为目标<c>元素后继续处理其子节点。 - 为每个需要重命名的子元素编写专属匹配模板:匹配原元素名称,输出新标签的同时保留原元素的属性与文本内容。
内容的提问来源于stack exchange,提问作者MandyA
相关产品推荐
相关产品推荐

