Page 1 of 1

convert xml to tree strcuture

Posted: Mon Mar 21, 2016 1:42 pm
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

Re: convert xml to tree strcuture

Posted: Tue Mar 22, 2016 5:32 pm
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