1

如何仅将命名空间添加到根元素?

我的 XML:

<Envelope>
    <from>
        <contents />
    </from>
</Envelope>

我想要的输出:

<Envelope xmlns:tns="Foo">
    <from>
        <contents />
    </from>
</Envelope>

我只能用这个得到“xmlns='Foo'”,而不是“xmlns:tns=..”:

<xsl:element name="{local-name()}" namespace="Foo" >
        <xsl:copy-of select="attribute::*"/>
        <xsl:apply-templates />
</xsl:element>
4

1 回答 1

2

这是一个完整的转换

<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:tns="Foo">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>

     <xsl:template match="node()|@*">
         <xsl:copy>
           <xsl:apply-templates select="node()|@*"/>
         </xsl:copy>
     </xsl:template>

     <xsl:template match="/*">
      <xsl:element name="{name()}">
       <xsl:copy-of select=
        "document('')/*/namespace::*[name()='tns']"/>
       <xsl:apply-templates/>
      </xsl:element>
     </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时

<Envelope>
    <from>
        <contents />
    </from>
</Envelope>

产生了想要的正确结果:

<Envelope xmlns:tns="Foo">
   <from>
      <contents/>
   </from>
</tns:Envelope>
于 2012-05-22T12:08:27.753 回答