如何使用XSLT移除XML命名空间前缀并重命名指定标签?
移除XML命名空间前缀并替换根元素的XSLT方案
没问题,我来帮你搞定这个XML转换需求——移除命名空间前缀,同时把根标签BusinessPartnerSUITEBulkReplicateRequest替换成Profiles,还完整保留内部的节点结构。
实现思路
核心通过XSLT模板匹配处理两类场景:
- 精准匹配原根元素,直接输出新的
Profiles标签 - 对其他所有带命名空间的元素,移除前缀保留原始元素名和内部内容
完整XSLT代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:n0="http://sap.com/xi/SAPGlobal20/Global"> <!-- 复制文本、注释、处理指令等非元素节点 --> <xsl:template match="text()|comment()|processing-instruction()"> <xsl:copy/> </xsl:template> <!-- 匹配原根元素,替换为Profiles标签 --> <xsl:template match="n0:BusinessPartnerSUITEBulkReplicateRequest"> <Profiles> <xsl:apply-templates select="@*|node()"/> </Profiles> </xsl:template> <!-- 匹配所有带命名空间的元素,移除前缀保留元素名 --> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> </xsl:stylesheet>
转换效果验证
输入XML:
<n0:BusinessPartnerSUITEBulkReplicateRequest xmlns:n0="http://sap.com/xi/SAPGlobal20/Global" xmlns:prx="urn:sap.com:proxy:L52:/1SAI/TAS31250ABB49732A386280:804"> <ProfileData> <Data>ACD</Data> </ProfileData> </n0:BusinessPartnerSUITEBulkReplicateRequest>
输出XML:
<Profiles> <ProfileData> <Data>ACD</Data> </ProfileData> </Profiles>
这个方案不仅完成了你指定的根元素替换和前缀移除,还能兼容后续新增的带命名空间元素,同时保留文本、注释等非元素节点,适配性更强。
内容的提问来源于stack exchange,提问作者DPUser
相关产品推荐
相关产品推荐

