我是 XSLT 转换的新手。我的输出 xml 中存在名称空间映射问题。
输入 XML 是
<m:class xmlns:m="http://www.NotRequirednamespace.com">
<queryDetails>hello</queryDetails>
</m:class>
我的 XSLT 看起来像
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xpath-default-namespace="http://www.neededNamespace.com" xmlns:t="http://www.NotRequirednamespace.com" exclude-result-prefixes="t">
<xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="yes"/>
<!-- Stylesheet to remove all namespaces from a document -->
<!-- NOTE: this will lead to attribute name clash, if an element contains
two attributes with same local name but different namespace prefix -->
<!-- Nodes that cannot have a namespace are copied as such -->
<xsl:template match="/">
<school xmlns="http://www.neededNamespace.com">
<xsl:apply-templates/>
</school>
</xsl:template>
<!-- template to copy elements -->
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@* | node()"/>
</xsl:element>
</xsl:template>
<!-- template to copy attributes -->
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<!-- template to copy the rest of the nodes -->
<xsl:template match="comment() | text() | processing-instruction()">
<xsl:copy/>
</xsl:template>
</xsl:stylesheet>
输出 XML 是
<school xmlns="http://www.neededNamespace.com">
<class xmlns="">
<queryDetails>hello</queryDetails>
</class>
</school>
但我不想在元素类中使用名称默认命名空间 (xmlns="")。我喜欢将类元素的默认命名空间指定为“http://www.neededNamespace.com http://www.neededNamespace.com”。所以我需要输出 xml,如下所示。
<school xmlns="http://www.neededNamespace.com">
<class>
<queryDetails>hello</queryDetails>
</class>
</school>
我已经尝试了我所知道的所有选项。你能帮忙吗?提前致谢。
您真的需要所有这些代码吗?或者你只是用它作为咒语,希望它能以某种方式安抚邪灵?就像什么一样xpath-default-namespace
在 XSLT 1.0 样式表中做什么? (答案:要么什么也不做,要么产生致命错误 - 取决于您的处理器的容忍度)。
现在,如果您的 XML 示例具有代表性,那么您需要做的就是:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.neededNamespace.com">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<school>
<xsl:apply-templates/>
</school>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
其作用是:
- 创建一个名为的新根元素
<school>
;
- 为每个现有元素创建一个新元素,并使用现有元素的本地名称对其进行命名。
由于样式表包含一个声明默认命名空间, 所有新创建的元素(在上面的 #1 和 #2 中)将被放置在该命名空间中。
由于您的输入不包含任何属性,因此这应该是所需的所有代码。
如果您担心他们将来可能会添加一些您希望传递到输出的属性,只需将第二个模板更改为:
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
这假设属性将不在命名空间中 - 这是一个非常合理的假设。属性不会继承其父级的命名空间,并且很少看到作者将属性显式放置在命名空间中。仅当您确实需要预见这种可能性时,才需要额外的代码来处理属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)