[Home] [By Thread] [By Date] [Recent Entries]
At 2007-10-29 17:39 -0700, Sam Mesh wrote:
I need to transform XML from form_1 into form_2. Hopefully, this is well known FAQ. I haven't seen it asked before, but it is quite straight forward given the regularity of your element names under the request element. form_1. Plane/flat (not nested) structure with composite/compound/structured tags Like <struct1.param12.param123> below. ... form_2. Nested/hierarchical structure with simple/decomposed tags Like <struct1>...<param11>...<param12> below. I hope the solution below is helpful. The result matches your requirement, so if you haven't missed anything in your specification then this should do it. . . . . . . . . . . Ken
<xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <!--reconstitute the request element as needed-->
<xsl:template match="request">
<request>
<!--start by grouping all by the first of the names-->
<xsl:call-template name="group-this">
<xsl:with-param name="this" select="*"/>
</xsl:call-template>
</request>
</xsl:template><!--at each level of depth of a '.'-separated name, create a new group-->
<xsl:template name="group-this">
<xsl:param name="depth" select="1"/>
<xsl:param name="this"/>
<!--do the group for this part of the name-->
<xsl:for-each-group select="$this"
group-by="tokenize(name(.),'\.')[$depth]">
<!--constitute the new element-->
<xsl:element name="{current-grouping-key()}">
<!--determine if there are more to be grouped-->
<xsl:variable name="next-this"
select="current-group()[tokenize(name(.),'\.')[$depth+1]]"/>
<xsl:choose>
<xsl:when test="$next-this">
<!--yes there are more to be grouped, at next level of depth-->
<xsl:call-template name="group-this">
<xsl:with-param name="this" select="$next-this"/>
<xsl:with-param name="depth" select="$depth+1"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<!--nothing more to be grouped-->
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</xsl:element>
</xsl:for-each-group>
</xsl:template><!--identity for all other nodes-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template></xsl:stylesheet>
t:\ftemp>type mesh.xml
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/ ">
<soap:Header>
</soap:Header>
<soap:Body>
<request>
<struct1.param11>...</struct1.param11>
<struct2.param21>...</struct2.param21>
<struct1.param12.param123>...</struct1.param12.param123>
</request>
</soap:Body>
</soap:Envelope>t:\ftemp>call xslt2 mesh.xml mesh.xsl mesh.out t:\ftemp>type mesh.out
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/ ">
<soap:Header/>
<soap:Body>
<request>
<struct1>
<param11>...</param11>
<param12>
<param123>...</param123>
</param12>
</struct1>
<struct2>
<param21>...</param21>
</struct2>
</request>
</soap:Body>
</soap:Envelope>
t:\ftemp>rem Done!
|

Cart



