XSLT转型存在疑问

时间:2010-10-02 23:50:16

标签: xslt

我想编写一个xslt来将一个xml文件转换为另一个xml文件。源XML文件类似于以下

<orgs>
<organization revenue="10000">
  <name>foo</name>
</organization>
<organization parent="foo">
 <name>foo2</name>
</organization>
<organization parent="foo2">
 <name>foo3</name>
</organization>
</orgs>

输出xml应如下

<orgo>
<organization revenue="10000">
 <name>foo</name>
 <organization>
  <name>foo2</name>
  <organization><name>foo3</name></organization>
 </organization>
</organization>
</orgo>

到目前为止,我已尝试按如下方式编写xsl xslt

1 个答案:

答案 0 :(得分:1)

此转化

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

 <xsl:template match="node()">
     <xsl:copy>
       <xsl:apply-templates select="node()[1]"/>
       <xsl:apply-templates select="following-sibling::node()[1]"/>
     </xsl:copy>
 </xsl:template>

</xsl:stylesheet>

应用于提供的XML文档

<orgs>
    <organization revenue="10000">
        <name>foo</name>
    </organization>
    <organization parent="foo">
        <name>foo2</name>
    </organization>
    <organization parent="foo2">
        <name>foo3</name>
    </organization>
</orgs>

生成所需的正确输出

<orgs>
   <organization>
      <name>foo</name>
      <organization>
         <name>foo2</name>
         <organization>
            <name>foo3</name>
         </organization>
      </organization>
   </organization>
</orgs>

如果<organization>元素的顺序是随机的,请参阅以下XML文档

<orgs>
    <organization parent="foo2">
        <name>foo3</name>
    </organization>
    <organization parent="foo">
        <name>foo2</name>
    </organization>
    <organization revenue="10000">
        <name>foo</name>
    </organization>
</orgs>

此转换产生想要的结果

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

 <xsl:template match="/*">
     <xsl:copy>
       <xsl:apply-templates select="organization[not(@parent)]"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="organization">
     <xsl:copy>
       <xsl:copy-of select="node()"/>
       <xsl:apply-templates select="../organization[@parent=current()/name]"/>
     </xsl:copy>
 </xsl:template>
</xsl:stylesheet>