我想要一个转换,以便在文档根元素上声明文档中的所有命名空间。以便<a>
<ns1:b xmlns:ns1="urn:ns1"/>
<ns2:c xmlns:ns2="urn:ns2"/>
</a>
变成<a xmlns:ns1="urn:ns1" xmlns:ns2="urn:ns2">
<ns1:b/>
<ns2:c/>
</a>
命名空间是否出现在本地声明中并不重要,关键是它们都应该具有全局作用域。
最佳答案
不知道为什么命名空间声明的位置应该有所不同。不过,如果您愿意,您可以尝试以下操作:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/a">
<a xmlns:ns1="urn:ns1" xmlns:ns2="urn:ns2">
<xsl:apply-templates/>
</a>
</xsl:template>
</xsl:stylesheet>
或者以更通用的方式:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<xsl:copy>
<xsl:copy-of select="//namespace::*"/>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这些可能有效,也可能无效,这取决于您的 XSLT 处理器的奇思妙想。
关于xslt - 在根元素上声明所有命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61866331/