XSLT:使用每个顺序节点重复一个节点



这是html:

<html>
    <div>
        <div class="theheader">The first header</div>
    </div>
    <div class="thecontent">
        <div class="col1">Col 1 </div>
        <div class="col2">Col 2 </div>
    </div>
    <div class="thecontent">
        <div class="col1">Col 3 </div>
        <div class="col2">col 4 </div>
    </div>
    <div>
        <div class="theheader">The second header</div>
    </div>
    <div class="thecontent">
        <div class="col1">Col 5 </div>
        <div class="col2">Col 6 </div>
    </div>
    <div class="thecontent">
        <div class="col1">Col 7 </div>
        <div class="col2">Col 8 </div>
    </div>
</html>

这是XSL:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" omit-xml-declaration="yes" indent="no"/>
    <xsl:template match="div[@class='theheader']" />
    <xsl:template match="div[@class='thecontent']">
        <xsl:value-of select="//div[@class='theheader']" /><xsl:text>: </xsl:text>
        <xsl:value-of select="." />
        <xsl:text>&#10;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

这是输出:

The first header: Col 1 Col 2
The first header: Col 3 col 4
The first header: Col 5 Col 6
The first header: Col 7 Col 8

所需的输出:

The first header: Col 1 Col 2
The first header: Col 3 col 4
The second header: Col 5 Col 6
The second header: Col 7 Col 8

如何完成?XSLT 1.0首选。

也尝试了:

<xsl:value-of select=".//div[@class='theheader']" /><xsl:text>: </xsl:text>

(//之前的点),并且没有输出标头。谁能告诉我为什么?编辑了示例,因为第一版太简化了。现在,告诉我这太多的代码。希望此盈余文本有所帮助。

您需要移动代码以将标题从模板匹配的" theheader"输出到模板匹配的" thecontent"中,以便重复。您还需要使用preceding-sibling轴才能获得所需的DIV。

尝试此XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" omit-xml-declaration="yes" indent="no"/>
    <xsl:template match="div[@class='theheader']" />
    <xsl:template match="div[@class='thecontent']">
        <xsl:value-of select="preceding-sibling::div[div/@class='theheader'][1]/div" /><xsl:text>: </xsl:text>
        <xsl:for-each select="div">
            <xsl:value-of select="." />
        </xsl:for-each>
        <xsl:text>&#10;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

编辑:响应您对theheader的评论,可能会更深入,请尝试其中一种表达式

<xsl:value-of select="preceding-sibling::div[descendant::div/@class='theheader'][1]//div[@class='theheader']" />
<xsl:value-of select="preceding::div[@class='theheader'][1]" />

最新更新