Xml 仅使用XSLT重命名根标记

Xml 仅使用XSLT重命名根标记,xml,xslt,Xml,Xslt,我正在尝试重命名下面xml的根标记 <?xml version="1.0" encoding="UTF-8"?> <root xmlns="http://ws.apache.org/ns/synapse"> <aaa> <bbb> <ccc>123</ccc> <ggg>2010.2</ggg> </bbb> <

我正在尝试重命名下面xml的根标记

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://ws.apache.org/ns/synapse">
   <aaa>
      <bbb>
         <ccc>123</ccc>
         <ggg>2010.2</ggg>
      </bbb>
   </aaa>
   <ddd>
      <eee>112</eee>
      <fff>234</fff>
   </ddd>
   <ddd>
      <eee>456</eee>
      <fff>345</fff>
   </ddd>
</root>

123
2010.2
112
234
456
345
我正试图使用xslt来理解以下xml

<?xml version="1.0" encoding="UTF-8"?>
<zzz xmlns="http://ws.apache.org/ns/synapse">
   <aaa>
      <bbb>
         <ccc>123</ccc>
         <ggg>2010.2</ggg>
      </bbb>
   </aaa>
   <ddd>
      <eee>112</eee>
      <fff>234</fff>
   </ddd>
   <ddd>
      <eee>456</eee>
      <fff>345</fff>
   </ddd>
</zzz>

123
2010.2
112
234
456
345
我尝试使用下面的XSLT来获取上面的xml

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

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

并返回与输入相同的响应

但是,如果根标记没有名称空间,此xslt将返回预期的响应


有人能帮我吗。

使用以下脚本:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:syn="http://ws.apache.org/ns/synapse">
  <xsl:output indent="yes"/>

  <xsl:template match="syn:root">
    <xsl:element name="zzz" namespace="http://ws.apache.org/ns/synapse">
      <xsl:apply-templates select="@* | node()" />
    </xsl:element>
  </xsl:template>

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

所需的更改包括:

  • 在样式表标记中包含默认的源命名空间, 给它起个名字(我用syn)
  • 将匹配从
    root
    更改为
    syn:root
  • 使用名称空间规范创建主元素(zzz)

假设要重命名根元素,同时保留其原始名称空间,可以执行以下操作:

XSLT1.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>

<!-- rename root (keep namespace) -->
<xsl:template match="/*">
    <xsl:element name="zzz" namespace="{namespace-uri()}">
        <xsl:apply-templates select="@* | node()" />
    </xsl:element>
</xsl:template>

</xsl:stylesheet>


谢谢您的回复。是否有任何方法可以动态获取名称空间?您的
$ns
变量将包含通用XML名称空间。在这里查看您的结果:您的问题不清楚。名称空间是名称的一部分;如果要重命名根元素,必须指定新名称应使用的名称空间(如果有)。也不清楚你在下面的评论中所说的“动态”是什么意思。