如何使用 XSL:Key 在 XSLT 2.0 中获取以下同级

How to use XSL:Key to get the following-sibling in XSLT 2.0

我 XML 嵌入了富文本格式,大致如下所示:

 <?xml version="1.0" encoding="UTF-8"?>
 <document>
     <richtext>
         <pardef/>
         <par><run>This is the </run><run>preamble.</run></par>
         <pardef list='bullet'/>
         <par><run>This is the </run><run>first bullet.</run></par>
         <par><run>This is the second </run><run>bullet.</run></par>
      </richtext>
 </document>

我正在尝试生成以下 HTML:

 <p>This is the preamble.</p>
 <ul>
    <li>This is the first bullet</li>
    <li>This is the second bullet</li>
 <ul>

我尝试了以下 XSL,但它不起作用。我觉得我需要使用 FOLLOWING-SIBLING 但我不确定如何使用。

    <xsl:choose>

        <xsl:when test="document/richtext/pardef[@list] ='bullet'">
            <ul>
                <xsl:for-each select="document/richtext/par/run">
                    <li>
                        <xsl:for-each select="run">
                            <xsl:value-of select="."/> 
                        </xsl:for-each>
                    </li>
                </xsl:for-each>   

            </ul>
        </xsl:when>           

        <xsl:otherwise>
            <p>
                <xsl:for-each select="document/richtext/par">
                    <p>
                        <xsl:for-each select="run">
                            <xsl:value-of select="."/> 
                        </xsl:for-each>
                    </p>
                </xsl:for-each>
            </p>
        </xsl:otherwise>    

    </xsl:choose>            

XSLT 2.0 和您的 "design" 的一种方法:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:key name="key-for-par" match="document/richtext/par" use="generate-id(preceding-sibling::pardef[1])"/>
    <xsl:output indent="yes"/>

    <xsl:template match="/">
        <xsl:apply-templates select="document/richtext/pardef" />
    </xsl:template>

    <xsl:template match="pardef[@list = 'bullet']">
        <ul>
            <xsl:for-each select="key('key-for-par', generate-id(.))">
                <li>
                    <xsl:value-of select="run" separator=""/>
                </li>
            </xsl:for-each>
        </ul>
    </xsl:template>

    <xsl:template match="pardef[not(@list)]">
        <p>
            <xsl:for-each select="key('key-for-par', generate-id(.))">
                <p>
                    <xsl:value-of select="run" separator=""/>
                </p>
            </xsl:for-each>
        </p>
    </xsl:template>

</xsl:stylesheet>

编辑 1: 改进版本。