XSL显示相同级别

时间:2015-07-22 15:59:23

标签: xml xslt

我有像这样的xml数据。

    <commentList>
     <item>
        <comment_id>2</comment_id>
        <discussion_id>3</discussion_id>
        <replyTo>0</replyTo>
        <Text>This is a test comment</Text>
     </item>
     <item>
        <comment_id>3</comment_id>
        <discussion_id>3</discussion_id>
        <replyTo>0</replyTo>
        <Text>Hello</Text>
     </item>
     <item>
        <comment_id>4</comment_id>
        <discussion_id>3</discussion_id>
        <replyTo>2</replyTo>
        <Text>Reply to This is a test comment</Text>
     </item>
    </commentList>

replyTo - 父评论ID(0 = root)

replyTo最多一级。

我只是想先显示评论和相关回复。然后下一个评论和回复等等。有这种存档的最佳方式吗?提前致谢。

按照上述问题预期输出。

This is a test comment
- Reply to This is a test comment
Hello

1 个答案:

答案 0 :(得分:1)

使用key将项目链接到他们的回复很方便。

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>

<xsl:key name="replies" match="item" use="replyTo" />

<xsl:template match="/commentList">
    <!-- select starter items -->
    <xsl:apply-templates select="item[replyTo=0]"/> 
</xsl:template>

<xsl:template match="item">
    <xsl:if test="replyTo > 0">
        <xsl:text>- </xsl:text>
    </xsl:if>
    <xsl:value-of select="Text"/>
    <xsl:text>&#10;</xsl:text>
    <!-- append replies -->
    <xsl:apply-templates select="key('replies', comment_id)"/>  
</xsl:template>

</xsl:stylesheet>

这对级别数量没有限制。例如,给出以下测试输入:

<强> XML

<commentList>
      <item>
        <comment_id>1</comment_id>
        <replyTo>0</replyTo>
        <Text>One</Text>
     </item>
     <item>
        <comment_id>2</comment_id>
        <replyTo>0</replyTo>
        <Text>Two</Text>
     </item>
     <item>
        <comment_id>3</comment_id>
        <replyTo>1</replyTo>
        <Text>Reply to One</Text>
     </item>
    <item>
        <comment_id>4</comment_id>
        <replyTo>2</replyTo>
        <Text>Reply to Two</Text>
     </item>
     <item>
        <comment_id>5</comment_id>
        <replyTo>1</replyTo>
        <Text>Reply to One</Text>
     </item>
     <item>
        <comment_id>6</comment_id>
        <replyTo>3</replyTo>
        <Text>Reply to Three</Text>
     </item>
     <item>
        <comment_id>7</comment_id>
        <replyTo>3</replyTo>
        <Text>Reply to Three</Text>
     </item>
     <item>
        <comment_id>8</comment_id>
        <replyTo>4</replyTo>
        <Text>Reply to Four</Text>
     </item>
</commentList>

结果将是:

One
- Reply to One
- Reply to Three
- Reply to Three
- Reply to One
Two
- Reply to Two
- Reply to Four