XSLT:向非根元素添加显式xmlns decalaration

时间:2013-12-31 15:40:29

标签: xslt

我的源文件如下所示:

                                             

对于我的目标文件,我必须删除所有名称空间,并在employee标记后添加以下文本:

的xmlns = “X-模式:文件:/// C:\ LAVIE \ tksql \ EMPLOYEE-SCHEMA.XML”

    

我创建了一个XSLT映射,它成功地删除了ns,但我无法在每个雇员标记中添加显式xmlns语句。

我的XSLT:

<xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="no"/>

<!-- 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 -->

<!-- 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>

有什么想法添加到XSLT以在每个员工标记之后添加显式xmlns吗?

由于

号Yoni

3 个答案:

答案 0 :(得分:1)

使用

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="urn:C:\lavie\tksql\Employee-Schema.Xsd" exclude-result-prefixes="ns1">

然后添加模板

<xsl:template match="ns1:employee | ns1:employee//*">
  <xsl:element name="{local-name()}" namespace="x-schema:file:///C:\lavie\tksql\EMPLOYEE-SCHEMA.XML">
    <xsl:apply-templates select="@* | node()"/>
  </xsl:element>
</xsl:template>

答案 1 :(得分:1)

XSLT在XPath / XDM数据模型上运行,名称空间声明不是该模型的一部分。相反,名称空间以两种方式表现出来:元素和属性名称有三个部分(前缀,名称空间uri和本地名称),以及元素具有名称空间节点的事实。

通常(包括在这种情况下,我相信)你不应该担心命名空间节点或命名空间声明:如果你生成具有正确的三部分名称的元素,命名空间声明将在结果树时自行处理是序列化的。

当您使用xsl:element时,您可以通过以下两种方式之一控制生成元素的三部分名称:

(1) <xsl:element name="pre:local"/>

将元素放入绑定(在样式表中)到前缀“pre”的命名空间中。如果您知道静态需要什么名称空间,则可以使用此表单。

(2) <xsl:element name="local" namespace="{$ns}"/>
当动态计算命名空间(在运行时)时,

非常有用。

答案 2 :(得分:0)

注意:由于XML命名空间继承到子(包含)元素,因此XML序列化程序可能决定不输出冗余声明。如果您的XSLT处理器具有该优化位,您可能会发现使用此工具无法在每个元素上放置显式xmlns =。

当然,由于XML命名空间确实继承了子元素,因此不清楚为什么您认为需要在每个元素上重新声明命名空间绑定。所有你真正需要的是将它们绑定到那个命名空间......马丁的答案将为你做。