convert xml to tree strcuture

Here should go questions about transforming XML with XSLT and FOP.
frontendBeginner
Posts: 1
Joined: Mon Mar 21, 2016 1:28 pm

convert xml to tree strcuture

Post by frontendBeginner »

Hi ,

I am new to XML. I want to convert the below xml to one like output. Is it possible.?? if yes how do i do it??

Code: Select all

 INPUT
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Rowsets>
<Rowset>
<Row>
<GroupName>Parent1</GroupName>
<ParentGroupName>Root</ParentGroupName>
</Row>
<Row>
<GroupName>Child1</GroupName>
<ParentGroupName>Parent1</ParentGroupName>
</Row>
<Row>
<GroupName>Child2</GroupName>
<ParentGroupName>Parent1</ParentGroupName>
</Row>
<Row>
<GroupName>Child3</GroupName>
<ParentGroupName>Parent1</ParentGroupName>
</Row>
<Row>
<GroupName>Parent2</GroupName>
<ParentGroupName>Root</ParentGroupName>
</Row>
<Row>
<GroupName>Child1</GroupName>
<ParentGroupName>Parent2</ParentGroupName>
</Row>
<Row>
<GroupName>Child2</GroupName>
<ParentGroupName>Parent2</ParentGroupName>
</Row>
<Row>
<GroupName>Child3</GroupName>
<ParentGroupName>Parent2</ParentGroupName>
</Row>
</Rowset>
</Rowsets>

Code: Select all


OUTPUT 
Root
Parent1
Child1
Child2
Child3
Parent2
Child1
Child2
Child3
adrian
Posts: 2855
Joined: Tue May 17, 2005 4:01 pm

Re: convert xml to tree strcuture

Post by adrian »

Hi,

This does what you want:

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">

<xsl:output method="xml" indent="yes"/>

<xsl:variable name="root" select="/"/>

<xsl:template match="/">
<xsl:call-template name="createChild">
<xsl:with-param name="childName" select="'Root'"/>
</xsl:call-template>
</xsl:template>

<xsl:template name="createChild">
<xsl:param name="childName"/>
<xsl:element name="{$childName}">
<xsl:for-each select="$root//Row[ParentGroupName/text() = $childName]">
<xsl:call-template name="createChild">
<xsl:with-param name="childName" select="GroupName/text()"/>
</xsl:call-template>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Note that this doesn't check for loops. So you can get it stuck if the structure is not tree-like.

Regards,
Adrian
Adrian Buza
<oXygen/> XML Editor, Schema Editor and XSLT Editor/Debugger
http://www.oxygenxml.com
Post Reply