我试图将此XML层次结构转换为HTML表格
<TopTerm Id="1" Name="Company">
<narrower Id="2" Name="Office">
<narrower Id="2.1" Name="Desk">
<narrower Id="2.1.1" Name="PC"/>
</narrower>
<narrower Id="2.2" Name="Cabinet">
<narrower Id="2.2.1" Name="Folder"/>
<narrower Id="2.2.2" Name="Files"/>
</narrower>
</narrower>
</TopTerm>
期望的输出:
<table>
<tr>
<th>Level 1</th>
<th>Level 2</th>
<th>Level 3</th>
<th>Level 4</th>
<th>Id</th>
</tr>
<tr>
<td>Company</td>
<td>Office</td>
<td></td>
<td></td>
<td>2</td>
</tr>
<tr>
<td>Company</td>
<td>Office</td>
<td>Desk</td>
<td></td>
<td>2.1</td>
</tr>
</table>
基本上,它需要为每个层次结构级别创建1 <tr>
并包含其祖先。
我使用这个XSLT
<xsl:template match="/">
<table>
<tr>
<th>Level 1</th>
<th>Level 2</th>
<th>Level 3</th>
<th>Level 4</th>
<th>Id</th>
</tr>
<xsl:apply-templates select="//TopTerm"/>
</table>
</xsl:template>
<xsl:template match="TopTerm">
<tr>
<td><xsl:value-of select="@Name"/></td>
<td></td>
<td></td>
<td></td>
<td><xsl:value-of select="@Id"/></td>
</tr>
<xsl:apply-templates select="descendant-or-self::narrower"/>
</xsl:template>
<xsl:template match="narrower">
<tr>
<xsl:for-each select="ancestor-or-self::*">
<td><xsl:value-of select="@Name"/></td>
</xsl:for-each>
<td><xsl:value-of select="@Id"/></td> <!--Problem is here-->
</tr>
</xsl:template>
问题是Id的<td>
并不总是在正确的位置,因为每个级别的祖先数量不同。如何为每个节点获取正确的ID并将其放入正确的Id列?
答案 0 :(得分:0)
我发现了另一种方法,我可以通过计算当前节点的祖先数来添加所需的<td>
。
<xsl:template match="narrower">
<tr>
<xsl:for-each select="ancestor-or-self::*">
<td>
<xsl:value-of select="@Name"/>
</td>
</xsl:for-each>
<xsl:if test="count(ancestor-or-self::*) = 1">
<td/>
<td/>
<td/>
<td/>
</xsl:if>
<xsl:if test="count(ancestor-or-self::*) = 2">
<td/>
<td/>
</xsl:if>
<xsl:if test="count(ancestor-or-self::*) = 3">
<td/>
</xsl:if>
<td>
<xsl:value-of select="@Id"/>
</td>
</tr>
</xsl:template>