首页 > 解决方案 > 如何遍历多个 XML 输入文件并将相关的属性值复制到 HTML 输出表中的一行

问题描述

我正在尝试遍历几个输入文件,在 HTML 输出文件中创建一个表格,其中每一行对应一个评论,但我无法获得相应的 @date 值并将其复制到表格的相应单元格中。任何帮助将不胜感激。

XML 输入文件

文件 1

<review rid="id_001" date="2018-03-20">
    <pc pid="pc_001">
        <result>...</result>
    </pc>
    <pc pid="pc_002">
        <result>...</result>
    </pc>
</review>

文件 2

<review rid="id_002" date="2018-05-19">
    <pc pid="pc_001">
        <result>...</result>
    </pc>
    <pc pid="pc_002">
        <result>...</result>
    </pc>
</review>

所需的 HTML 输出

<!-- @pid value outside the table as header. --> 
<table>    
    <tr>
        <td>Review ID</td>
        <td>Date</td>
        <td>Result</td>
    </tr>
    <tr>
        <td>001</td>
        <td>2018-03-20</td>
        <td>...</td>
    </tr>
        <td>002</td>
        <td>2018-05-19</td>
        <td>...</td>
    </tr>
</table>

XSLT

<xsl:variable name="files" select="collection('../?select=*.xml')"/>
<xsl:template match="/">
<!-- @pid value outside the table as header. --> 
    <table>
        <tr>
            <td>Review ID</td>
            <td>Date</td>
            <td>Result</td>
        </tr>
        <xsl:if test="$files">          
            <xsl:for-each select="distinct-values($files/review/@rid)">
                <xsl:variable name="currentRid" select="distinct-values($files/review/@rid)"/>            
                <xsl:variable name="currentPid" select="distinct-values($files/review/pc/@pid)"/> 
                <tr>
                    <td>                  
                        <xsl:value-of select="."/>
                    </td>
                    <td>
                        <xsl:for-each select="distinct-values($files/review/@date)">                     
                            <xsl:value-of select="."/>
                        </xsl:for-each>
                    </td>
                    <td>
                        <xsl:value-of select="distinct-values($files/review[@rid=$currentRid]/pc[@pid=$currentPid]/result)"/>
                    </td>
                </tr>
            </xsl:for-each>
        </xsl:if>      
        </tr>
    </table>
</xsl:template>

标签: xsltxslt-2.0

解决方案


问题是您试图迭代所有 review元素的@date值。for-each将表达式限制为与您在下一个表达式中所做review的类似的元素可以为您提供所需的输出。所以改变current() ridxsl:value-of

<xsl:for-each select="distinct-values($files/review/@date)">

<xsl:for-each select="distinct-values($files/review[@rid=current()]/@date)">  

我无法估计这是否xsl:for-each是必要的——这取决于大局——但也许下面的表达式就足够了

<xsl:value-of select="$files/review[@rid=current()]/@date"/>

推荐阅读