Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Flatten XML hierarchy 1

Status
Not open for further replies.

MikeAJ

Programmer
May 22, 2002
108
0
0
US
Hi XSL Gurus,
I need to flatten an XML hierarchy that can go many levels deep, to an XML doc that's only 1 level deep. In the flattened form, though, it must be able to reference what it's parent node used to be.

Here's an example:
Code:
<PACKAGE id = "1">
   <OPTION_CLASS id = "2">
      <OPTION_CLASS id = "3">
         <PART id = "4"/>
         <OPTION_CLASS id = "5">
            <PART id = "6"/>
         </OPTION_CLASS>
      </OPTION_CLASS>
      <PART id = "7"/>
   </OPTION_CLASS>
   <OPTION_CLASS id = "8">
      <PART id = "9"/>
   </OPTION_CLASS>
   <PART id = "10"/>
   <PART id = "11"/>
</PACKAGE>

to this:
Code:
<PACKAGE id = "1">
   <OPTION_CLASS id = "2" parent_id = "1">
      <PART id = "7"/>
   </OPTION_CLASS>
   <OPTION_CLASS id = "3"  parent_id = "2">
      <PART id = "4"/>
   </OPTION_CLASS>
   <OPTION_CLASS id = "5" parent_id = "3">
      <PART id = "6"/>
   </OPTION_CLASS>
   <OPTION_CLASS id = "8" parent_id = "1">
      <PART id = "9"/>
   </OPTION_CLASS>
   <PART id = "10"/>
   <PART id = "11"/>
</PACKAGE>

I've been looking around all day, and I can't find any leads. Can anyone point me in the right direction?

Thanks,
Mike
 
Are those id values really there, or is this just to illustrate? In other words, do you need to compute the parent node position?

Tom Morrison
 
This set out the logic.
[tt]
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="<xsl:eek:utput method="xml" version="1.0" encoding="utf-8" indent="yes" />
<xsl:template match="/">
<xsl:apply-templates select="*" />
</xsl:template>
<xsl:template match="PACKAGE">
<xsl:copy>
<xsl:apply-templates select="*|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:copy-of select="." />
</xsl:template>
<xsl:template match="PART">
<xsl:copy-of select="." />
</xsl:template>
<xsl:template match="OPTION_CLASS">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:attribute name="parent_id">
<xsl:value-of select="parent::*/@id" />
</xsl:attribute>
<xsl:apply-templates select="PART" />
</xsl:copy>
<xsl:apply-templates select="OPTION_CLASS" />
</xsl:template>
</xsl:stylesheet>
[/tt]
 
Thanks guys! Tsuji, your example worked! Very cool stuff! I learned a lot from it!

Thanks again,
Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top