I need to take this xml…
<root>
<item id=’1’ parent_id=’0’>ONE</item>
<item id=’2’ parent_id=’1’>TWO</item>
<item id=’3’ parent_id=’1’>THREE</item>
<item id=’4’ parent_id=’2’>FOUR</item>
<item id=’5’ parent_id=’0’>FIVE</item>
</root>
And produce this xhtml…
<div class=’parent’>ONE</div>
<div class=’child’>
<di开发者_开发知识库v class=’parent’>TWO</div>
<div class=’child’>
<div class=’parent’>FOUR</div>
</div>
<div class=’parent’>THREE</div>
</div>
<div class=’parent’>FIVE</div>
I get how to collect the child nodes and put them under their parent, but I can’t grasp how to then skip over considering them as parents if I have already used them as children.
Tested the following, which appears to work
Apply all items at the root with parent_id = 0, then recursively iterate for any children..
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates select="root/item[@parent_id='0']"/>
</xsl:template>
<xsl:template match="item">
<div class="parent"><xsl:value-of select="."/></div>
<xsl:if test="count(../item[@parent_id=current()/@id]) != 0">
<div class="child">
<xsl:apply-templates select="../item[@parent_id=current()/@id]"/>
</div>
</xsl:if>
</xsl:template>
This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="kItemById" match="item" use="@id"/>
<xsl:key name="kItemByParentId" match="item" use="@parent_id"/>
<xsl:template match="root">
<xsl:apply-templates select="item[not(key('kItemById',@parent_id))]"/>
</xsl:template>
<xsl:template match="item">
<xsl:variable name="vChild" select="key('kItemByParentId',@id)"/>
<div class="parent">
<xsl:value-of select="."/>
</div>
<xsl:if test="$vChild">
<div class="child">
<xsl:apply-templates select="$vChild"/>
</div>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Output:
<div class="parent">ONE</div>
<div class="child">
<div class="parent">TWO</div>
<div class="child">
<div class="parent">FOUR</div>
</div>
<div class="parent">THREE</div>
</div>
<div class="parent">FIVE</div>
Note: Keys for cross references.
精彩评论