问题
I have a trouble getting the following result from a xml/xslt transformation:
<root>
<node>
<id>1</id>
<parentid></parentid>
<name>file 1</name>
<node>
<node>
<id>2</id>
<parentid></parentid>
<name>file 2</name>
<node>
<node>
<id>3</id>
<parentid>2</parentid>
<name>file 3</name>
<node>
<node>
<id>4</id>
<parentid></parentid>
<name>file 4</name>
<node>
<node>
<id>5</id>
<parentid>2</parentid>
<name>file 5</name>
<node>
</root>
i would like the output html to be something like:
<ul>
<li>file 1</li>
<li>file 2</li>
<ul>
<li>file 3</li>
<li>file 5</li>
</ul>
<li>file 4</li>
</ul>
回答1:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/root">
<ul>
<xsl:apply-templates select="node[string-length(parentid)=0]" />
</ul>
</xsl:template>
<xsl:template match="node">
<li>
<xsl:value-of select="name"/>
</li>
<xsl:variable name="children" select="parent::*/node[parentid=current()/id]" />
<xsl:if test="$children">
<ul>
<xsl:apply-templates select="$children" />
</ul>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
回答2:
The key (no pun intended) is to use an <xsl:key>
to set up the parent-child relationship. Once that is defined, the rest is easy.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:key name="getchildren" match="node" use="parentid"/>
<xsl:template match="root">
<ul>
<xsl:apply-templates
select="node[parentid[not(normalize-space())]]"/>
</ul>
</xsl:template>
<xsl:template match="node">
<li><xsl:value-of select="name"/></li>
<xsl:variable name="children" select="key( 'getchildren', id )"/>
<xsl:if test="$children">
<ul><xsl:apply-templates select="$children"/></ul>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/5840931/xslt-group-parent-child