简体   繁体   中英

Best way to map elements of xml in xslt

I have the below format of xml.

<Floorplan IDValue="123" IDType="FloorplanID" IDRank="primary">
    <FloorplanInfo>info<FloorplanInfo>  
</Floorplan>
<Floorplan IDValue="456" IDType="FloorplanID" IDRank="primary">
    <FloorplanInfo>info<FloorplanInfo>  
</Floorplan>

<unit id = abc1 floorplanid = 123>
    <unitinfo>info</unitinfo>
<unit>
<unit id = abc2 floorplanid = 123>
    <unitinfo>info</unitinfo>
<unit>
<unit id = abc3 floorplanid = 456>
    <unitinfo>info</unitinfo>
 <unit>
 <unit id = abc4 floorplanid = 456>
    <unitinfo>info</unitinfo>
 <unit>

Based on the value of the floorplan id's in units i want to map them to the Floorplans and produce an xml of the below format. is this is possible using xslt and what could be the best approach. I am not sure if i have explained in my question in a better way but the example should do it.

<Floorplan IDValue="123" IDType="FloorplanID" IDRank="primary">
  <FloorplanInfo>info<FloorplanInfo>    
  <unit id = abc1 floorplanid = 123>
    <unitinfo>info</unitinfo>
   <unit>
  <unit id = abc2 floorplanid = 123>
     <unitinfo>info</unitinfo>
  <unit>
</Floorplan>
<Floorplan IDValue="456" IDType="FloorplanID" IDRank="primary">
        <FloorplanInfo>info<FloorplanInfo>
 <unit id = abc3 floorplanid = 456>
        <unitinfo>info</unitinfo>
 <unit>
 <unit id = abc4 floorplanid = 456>
        <unitinfo>info</unitinfo>
  <unit>    
 </Floorplan>

Thanks in advance !!

This should work for you. FYI: I had to clean up the XML you posted because it was not well formed.

    <xsl:key name="myKey" match="unit" use="@floorplanid"/>

    <xsl:template match="Floorplan">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
        <xsl:apply-templates select="key('myKey', @IDValue)" mode="unitMode"/>
      </xsl:copy>
    </xsl:template>

    <!-- Suppress unit current nodes. -->
    <xsl:template match="unit"/>

    <!-- Use mode to add the new unit nodes.  -->
    <xsl:template match="unit" mode="unitMode">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM