开发者

XSLT Transformation doubt

开发者 https://www.devze.com 2023-01-18 07:23 出处:网络
I want to write an xslt to transform one xml file to another. The source XML file is like the following

I want to write an xslt to transform one xml file to another. The source XML file is like the following

<orgs>
<organizatio开发者_开发技巧n revenue="10000">
  <name>foo</name>
</organization>
<organization parent="foo">
 <name>foo2</name>
</organization>
<organization parent="foo2">
 <name>foo3</name>
</organization>
</orgs>

The output xml should be as follows

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

So far i've tried writing the xsl as follows

XSLT Transformation doubt


This transformation:

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

when applied on the provided XML document:

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

produces the wanted, correct output:

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

In case the order of <organization> elements is random, like in the following XML document:

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

this transformation produces the wanted result:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号