通过兄弟姐妹迭代直到特定元素类型

时间:2015-05-13 07:39:10

标签: xslt xslt-1.0

我有一个扁平的XML结构,如下所示:

<root>
    <header>First header</header>
    <type1>Element 1:1</type1>
    <type2>Element 1:2</type2>

    <header>Second header</header>
    <type1>Element 2:1</type1>
    <type3>Element 3:1</type3>

    <header>Third header</header>
    <type1>Element 3:1</type1>
    <type2>Element 3:2</type2>
    <type1>Element 3:3</type1>
    <type2>Element 3:4</type2>
</root>

Essentialy有一个未知数量的标题。在每个标题下,存在未知数量的元素(树不同类型)。每个标题下每种类型可以有零到多个元素。我无法控制这种结构,所以我无法改变/改进它。

我想要生成的是这个HTML:

<h2>First header</h2>
<table>
    <tr>
        <th>Type 1</th>
        <td>Element 1:1</td>
    </tr>
    <tr>
        <th>Type 2</th>
        <td>Element 1:2</td>
    </tr>
</table>

<h2>Second header</h2>
<table>
    <tr>
        <th>Type 1</th>
        <td>Element 2:1</td>
    </tr>
    <tr>
        <th>Type 3</th>
        <td>Element 2:2</td>
    </tr>
</table>

<h2>third header</h2>
<table>
    <tr>
        <th>Type 1</th>
        <td>Element 3:1</td>
    </tr>
    <tr>
        <th>Type 2</th>
        <td>Element 3:2</td>
    </tr>
    <tr>
        <th>Type 1</th>
        <td>Element 3:3</td>
    </tr>
    <tr>
        <th>Type 2</th>
        <td>Element 3:4</td>
    </tr>
</table>

每个标题都是一个HTML标题(第2级),然后我希望所有其他元素直到下一个标题显示在表格中。

我的第一个想法是创建一个与标题元素匹配的模板:

<xsl:template match="header">
    <h2><xsl:value-of select="text()" /></h2>
    <table>
        ???
    </table>
</xsl:template>

我想我可以取代&#34; ???&#34;代码遍历所有以下兄弟姐妹,直到下一个标题元素并将它们转换为表格行。

这是个好主意吗?

如果是,我该怎么办? 如果不是,那么什么是更好的解决方案?

我正在使用XSLT 1.0。

1 个答案:

答案 0 :(得分:2)

实现此目的的一种方法是使用密钥,通过前面的第一个header元素对非标头元素进行分组

<xsl:key name="type" match="*[not(self::header)]" use="generate-id(preceding-sibling::header[1])" />

然后,您只需选择header元素

即可开始
<xsl:apply-templates select="header" />

在匹配此header元素的模板中,您可以使用密钥获取与标题对应的所有type元素

<xsl:for-each select="key('type', generate-id())">

试试这个XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" />
    <xsl:key name="type" match="*[not(self::header)]" use="generate-id(preceding-sibling::header[1])" />

    <xsl:template match="root">
        <xsl:apply-templates select="header" />
    </xsl:template>

    <xsl:template match="header">
        <h2><xsl:value-of select="." /></h2>
        <table>
            <xsl:for-each select="key('type', generate-id())">
                <tr>
                    <th><xsl:value-of select="local-name()" /></th>
                    <th><xsl:value-of select="." /></th>
                </tr>
            </xsl:for-each>
        </table>
    </xsl:template>
</xsl:stylesheet>

注意,这并不包括将节点名称type1转换为Type 1的问题,但我会为您留下这个练习....

相关问题