XSLT使用外部文档中的信息对表进行排序

时间:2017-10-13 18:47:38

标签: xml sorting xslt

我遇到了这个任务的主要问题,我无法弄清楚如何进行排序。

我试图在XSLT中对表进行排序,我在那里导入.XSL。在这个.XSL中我引用了两个外部.XSL。输出应该是html。

mainXSL.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" media-type="image/svg" indent="yes" encoding="UTF-8"/>

                <xsl:variable name="fileA" select="document(/importFiles/docs/@fileA)" />
                <xsl:variable name="fileB" select="document(/importFiles/docs/@fileB)" />
    <xsl:template match="/">
        <html>
            <head>
                <title> 
                    Task1
                </title>
            </head>        
                <body>
                    <table align="center" border="1">
                        <tr>
                            <th>column_1</th>
                            <th>column_2</th>
                        </tr>

                        <xsl:for-each select="$fileA/letters/letter">
                            <xsl:sort select="." order="ascending"/>
                                <xsl:variable name="current_node" select="position()"/>
                                    <tr>                                  
                                        <td class="_fileA"><xsl:value-of select="." /></td>
                                        <td class="_fileB"><xsl:value-of select="$fileB//animal[$current_node]" /></td>
                                    </tr>
                            </xsl:for-each>
                    </body>
               </html> 
</xsl:template>

INDEX.XML

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="mainXSL.xsl"?>

<importFiles>
    <docs fileA = "fileA.xml" />
    <docs fileB = "fileB.xml" /> 
</importFiles>

fileA.xml

<?xml version="1.0" encoding="UTF-8"?>

        <letters>
            <letter>A</letter>
            <letter>C</letter>
            <letter>B</letter>
            <letter>E</letter>
            <letter>D</letter>
        </letters>

fileB.xml

<?xml version="1.0" encoding="UTF-8"?>

        <animals>
            <animal>dog</animal>
            <animal>horse</animal>
            <animal>cow</animal>
            <animal>snake</animal>
            <animal>spider</animal>
        </animals>

因此fileA.xml中的字母被附加到fileB.xml中同一行的动物

我现在得到的是一张桌子:

A - 狗

B - 马

C - 牛

D - 蛇

E - 蜘蛛

我想得到的是:

A - 狗

B - 牛

C - 马

D - 蜘蛛

< - > E - 蛇

我无法弄清楚如何在for-each循环之后将列排序在一起,只有column_1。 试图在这里找到类似的问题但无济于事。 我之前发过一个类似的问题并得到了正确答案,但我忘了将数字编辑成字母。使用position()时,使用数字会更容易。我假设在这种情况下,position()可以用作索引,但它是一个长镜头。我相信这有一个更简单的解决方案。

1 个答案:

答案 0 :(得分:2)

更改

<xsl:variable name="current_node" select="position()"/>

<xsl:variable name="orig-pos"><xsl:number/></xsl:variable>

然后使用

<xsl:value-of select="$fileB//animal[position() = $orig-pos]" />