Gra*_*ark 18 xslt xml-namespaces
我有一些XML声明了一个仅用于属性的命名空间,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<a xmlns:x="http://tempuri.com">
<b>
<c x:att="true"/>
<d>hello</d>
</b>
</a>
Run Code Online (Sandbox Code Playgroud)
我想使用XSL创建所选节点及其值的副本 - 摆脱属性.所以我想要的输出是:
<?xml version="1.0" encoding="UTF-8"?>
<b>
<c />
<d>hello</d>
</b>
Run Code Online (Sandbox Code Playgroud)
我有一些XSL几乎可以做到这一点,但我似乎无法阻止它将名称空间声明放在输出的顶级元素中.我的XSL是:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:apply-templates select="/a/b"/>
</xsl:template>
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
输出的第一个元素是<b xmlns:x="http://tempuri.com">而不是<b>.我已经尝试在XSL中声明命名空间并将前缀放在exclude-result-prefixes列表中,但这似乎没有任何效果.我究竟做错了什么?
更新:我发现通过在XSL中声明命名空间并使用extension-element-prefixes属性工作,但这似乎不正确!我想我可以使用它,但我想知道为什么exclude-result-prefixes不起作用!
更新:实际上,这个extension-element-prefixes解决方案似乎只适用于XMLSpy的内置XSLT引擎,而不适用于MSXML.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:x="http://tempuri.com">
<xsl:template match="/">
<xsl:apply-templates select="/a/b"/>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name(.)}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:copy/>
</xsl:template>
<!-- This empty template is not needed.
Neither is the xmlns declaration above:
<xsl:template match="@x:*"/> -->
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
我在这里找到了解释.
Michael Kay写道:
exclude-result-prefixes只影响由文字结果元素从样式表复制的名称空间,它不影响从源文档复制名称空间.
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://tempuri.com"
exclude-result-prefixes="x"
>
<!-- the identity template copies everything 1:1 -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
<!-- this template explicitly cares for namespace'd attributes -->
<xsl:template match="@x:*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="." />
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)