仅使用XSLT重命名根标记

时间:2017-05-24 05:59:49

标签: 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>
   </aaa>
   <ddd>
      <eee>112</eee>
      <fff>234</fff>
   </ddd>
   <ddd>
      <eee>456</eee>
      <fff>345</fff>
   </ddd>
</root>

我试图使用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>

我尝试使用下面的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>

并返回与输入类似的相同响应。

但是,如果root标签没有名称空间,则此xslt将返回预期的响应。

有人可以帮助我。

2 个答案:

答案 0 :(得分:2)

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

XSLT 1.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>

答案 1 :(得分:-1)

使用以下脚本:

<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 )。