0

任何人都可以帮忙吗?我对 XSLT 很陌生,正在尝试构建一个元素表;我在下面简化了我的示例,并设法将输出输出到三个单元格的行上,但是行之间出现了不需要的空格 - 谁能告诉我我在这里做错了什么?

<apply-templates />我的比赛还需要两个吗?

非常感谢,亚历克斯

这是 XML:

<?xml version="1.0" encoding="iso-8859-1"?>
    <products>
        <r t='title1'>...</r>
        <r t='title2'>...</r>
        <r t='title3'>...</r>
        <r t='title4'>...</r>
        <r t='title5'>...</r>
        <r t='title6'>...</r>
        <r t='title7'>...</r>
        <r t='title8'>...</r>
        <r t='title9'>...</r>
    </products>

这是 XSL:

<!-- Rows -->
<xsl:template match="r[position() mod 3 = 1]">
    <div class="row">
        <xsl:apply-templates mode="cell" select="." />
        <xsl:apply-templates mode="cell" select="./following-sibling::r[not(position() > 2)]" />
    </div>
</xsl:template>

<!-- Cells -->
<xsl:template match="r" mode="cell">
    <div class="cell">
        <xsl:value-of select="@t"/>
    </div>
</xsl:template>

我的输出(注意行之间不需要的空格):

<div class="row">
    <div class="cell">Title1</div>
    <div class="cell">Title2</div>
    <div class="cell">Title3</div>
</div>









<div class="row">
    <div class="cell">Title4</div>
    <div class="cell">Title5</div>
    <div class="cell">Title6</div>
</div>









<div class="row">
    <div class="cell">Title7</div>
    <div class="cell">Title8</div>
    <div class="cell">Title9</div>
</div>
4

1 回答 1

0

好吧,首先不能是您的 XML,因为那是无效的。“有效”的 XML 文件不可能包含一个以上的根元素。您的 XML 在根中有九个“r”元素。

在尝试使用 XSLT 处理它之前先从有效的东西开始。

这个 XSL(注意我添加了一个模板来消除任何 text() 的匹配,因为否则你的“...”将被匹配:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="r[position() mod 3 = 1]">
    <div class="row">
        <xsl:apply-templates mode="cell" select="." />
        <xsl:apply-templates mode="cell" select="./following-sibling::r[not(position() > 2)]" />
    </div>
</xsl:template>

<xsl:template match="r" mode="cell">
    <div class="cell">
        <xsl:value-of select="@t"/>
    </div>
</xsl:template>

<xsl:template match="text()"/>
</xsl:stylesheet>

使用 Saxon 生成此输出(根本没有新行):

<?xml version="1.0" encoding="utf-8"?><div class="row"><div class="cell">title1</div><div class="cell">title2</div><div class="cell">title3</div></div><div class="row"><div class="cell">title4</div><div class="cell">title5</div><div class="cell">title6</div></div><div class="row"><div class="cell">title7</div><div class="cell">title8</div><div class="cell">title9</div></div>

如果您将 <xsl:output indent="yes"/> 添加到此,您将获得您期望的确切输出。除非您为 <products> 指定匹配项以输出根标记,否则您也会得到无效的 XML 输出。

于 2013-06-16T23:30:15.657 回答