如何使用 XSLT 重命名 XML 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7246666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 14:55:46 来源:igfitidea点击:
How do I rename XML tags using XSLT
提问by Srinivas
This is my XML-
这是我的 XML-
<CATALOG>
<NAME>C1</NAME>
<CD>
<NAME>Empire Burlesque</NAME>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<NAME>Hide your heart</NAME>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
I want to replace the NAME tag in catalog to CATALOG-NAME and the the NAME tag in CD's to CD-NAME which should make my xml look like this-
我想将目录中的 NAME 标记替换为 CATALOG-NAME,并将 CD 中的 NAME 标记替换为 CD-NAME,这应该使我的 xml 看起来像这样-
<CATALOG>
<CATALOG-NAME>C1</CATALOG-NAME>
<CD>
<CD-NAME>Empire Burlesque</CD-NAME>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<CD-NAME>Hide your heart</CD-NAME>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
回答by Wayne
Use the identity transform with overrides for the elements you want to rename:
对要重命名的元素使用带有覆盖的标识转换:
<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>
<xsl:template match="CD/NAME">
<CD-NAME><xsl:apply-templates select="@*|node()" /></CD-NAME>
</xsl:template>
<xsl:template match="CATALOG/NAME">
<CATALOG-NAME><xsl:apply-templates select="@*|node()" /></CATALOG-NAME>
</xsl:template>
</xsl:stylesheet>

