如何使用XSLT 1.0修改XML根元素命名空间?
修改XML根元素命名空间的XSLT实现
需求说明
需要将XML根元素ns1:ShipStatusResponse的命名空间从http://test.com/pi/VN/ABC/Invoice/10替换为http://test.com/pi/ERP/FICO/Invoice/10,同时保留所有子元素的内容和结构不变。
输入XML
<ns1:ShipStatusResponse xmlns:ns1="http://test.com/pi/VN/ABC/Invoice/10"> <httpcode>200</httpcode> <httpstatus>OK</httpstatus> <httpresult>test</httpresult> </ns1:ShipStatusResponse>
实现XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:oldns="http://test.com/pi/VN/ABC/Invoice/10" xmlns:newns="http://test.com/pi/ERP/FICO/Invoice/10"> <xsl:output method="xml" indent="yes"/> <!-- 匹配原根元素,生成新命名空间下的同名元素 --> <xsl:template match="oldns:ShipStatusResponse"> <ns1:ShipStatusResponse xmlns:ns1="http://test.com/pi/ERP/FICO/Invoice/10"> <!-- 复制所有子节点,保留原内容 --> <xsl:copy-of select="node()"/> </ns1:ShipStatusResponse> </xsl:template> <!-- 匹配其他节点,直接复制 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
关键说明
- 声明原命名空间为
oldns、新命名空间为newns,方便精准匹配和引用 - 专门匹配原根元素,创建带有新命名空间的根元素并指定前缀
ns1 - 用
<xsl:copy-of>直接复制所有子节点,确保子元素内容、结构完全保留 - 通用模板匹配其余所有节点,保证未特殊处理的节点原样输出
输出XML
<ns1:ShipStatusResponse xmlns:ns1="http://test.com/pi/ERP/FICO/Invoice/10"> <httpcode>200</httpcode> <httpstatus>OK</httpstatus> <httpresult>test</httpresult> </ns1:ShipStatusResponse>
内容的提问来源于stack exchange,提问作者Kratos
相关产品推荐
相关产品推荐

