Reputation: 37
I have the following sample XML with me :
<root>
<Entities>
<Entity>
<property type=”Name”>Name1</property>
<property type=”Parent_id”>-1</property>
<property type=”id”>1</property>
</Entity>
<Entity>
<property type=”Name”>Name2</property>
<property type=”Parent_id”>1</property>
<property type=”id”>2</property>
</Entity>
<Entity>
<property type=”Name”>Name3</property>
<property type=”Parent_id”>2</property>
<property type=”id”>3</property>
</Entity>
<Entity>
<property type=”Name”>Name4</property>
<property type=”Parent_id”>2</property>
<property type=”id”>4</property>
</Entity>
<Entity>
<property type=”Name”>Name5</property>
<property type=”Parent_id”>3</property>
<property type=”id”>5</property>
</Entity>
</Entities>
</root>
The XML consists of entities, each of which has a parent id and a id. There is always one such entity whose Parent Id = -1, which means it is the root entity.
I want an XSL which can convert this kind of XML to a HTML UL, where in the parent child relation's are depicted.
For example, for the above sample, the output would be :
<ul>
<li>Name1</li>
<ul>
<li>Name2</li>
<ul>
<li>Name3</li>
<ul>
<li>Name5</li>
</ul>
<li>Name4</li>
</ul>
</ul>
</ul>
The XML is dynamic and the number of entities are not a constant numbers, the only thing which is guaranteed is the existence of the entity whose parent id is -1, which marks it as the root entity of all.
I have been trying to write XSLT's for this but ending up with long running thing and not able to think of any strategy to solve this issue.
Please help by throwing a life jacket,
Upvotes: 1
Views: 164
Reputation: 56182
Use:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<ul>
<xsl:apply-templates select="//Entity[property[@type = 'Parent_id'] = -1]"/>
</ul>
</xsl:template>
<xsl:template match="Entity">
<li>
<xsl:value-of select="property[@type = 'Name']"/>
</li>
<xsl:if test="../Entity[property[@type = 'Parent_id'] = current()/property[@type = 'id']]">
<ul>
<xsl:apply-templates select="../Entity[property[@type = 'Parent_id'] = current()/property[@type = 'id']]"/>
</ul>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Output:
<ul>
<li>Name1</li>
<ul>
<li>Name2</li>
<ul>
<li>Name3</li>
<ul>
<li>Name5</li>
</ul>
<li>Name4</li>
</ul>
</ul>
</ul>
Upvotes: 2