XSLT 1.0中xsl:copy-of冗余命名空间移除方案咨询
移除XSLT转换后冗余命名空间的解决方案
问题背景
给定XML文档:
<root xmlns:foo="foo" > <foo:a> <bar wibble="1"/> </foo:a> </root>
使用基于msxsl引擎的XSLT 1.0样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:foo="foo" exclude-result-prefixes="msxsl foo"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <bar> <xsl:copy-of select="root/foo:a/bar"/> </bar> </xsl:template> </xsl:stylesheet>
转换后得到结果:
<bar> <bar wibble="1" xmlns:foo="foo" /> </bar>
其中xmlns:foo="foo"为冗余命名空间,未被实际使用,需修改XSLT移除该冗余项以提升可读性。
解决方案
问题根源在于xsl:copy-of会复制节点上下文的命名空间(即便节点本身不属于该命名空间)。因此需替换copy-of为手动创建节点并复制属性的方式,避免继承冗余命名空间。
修改后的XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:foo="foo" exclude-result-prefixes="msxsl foo"> <xsl:output method="xml" indent="yes"/> <!-- 处理根节点,生成外层bar容器 --> <xsl:template match="/"> <bar> <xsl:apply-templates select="root/foo:a/bar"/> </bar> </xsl:template> <!-- 匹配目标bar节点,创建无冗余命名空间的新节点 --> <xsl:template match="bar"> <!-- 创建同名节点,默认处于无命名空间上下文 --> <xsl:element name="{local-name()}"> <!-- 复制节点所有属性 --> <xsl:copy-of select="@*"/> <!-- 递归处理子节点(若有),保持通用性 --> <xsl:apply-templates/> </xsl:element> </xsl:template> </xsl:stylesheet>
转换结果
执行修改后的XSLT,输出结果为:
<bar> <bar wibble="1" /> </bar>
冗余的xmlns:foo="foo"已被移除,符合可读性要求。
内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd
相关产品推荐
相关产品推荐

