【问题标题】:XSLT 1.0 grouping childs when followed by a certain nodeXSLT 1.0 在跟随某个节点时对子节点进行分组
【发布时间】:2013-06-14 10:10:12
【问题描述】:

输入xml:

<entry>
    <text>
        <p>xyz</p>
        <p>xyz</p>
        <p>xyz</p>
        <p>xyz</p>
        <author>abc</author>
        <p>xyz</p>
        <p>xyz</p>
        <p>xyz</p>
        <author>abc</author>
    </text>
</entry>

我正在使用 XSLT 1.0。

我想选择所有&lt;p&gt; 元素直到下一个&lt;author&gt; 元素,并将它们(与下一个&lt;author&gt; 元素一起)分组到一个新的&lt;div&gt; 元素下。所以预期的输出如下所示:

<entry>
    <text>
      <div>
        <p>xyz</p>
        <p>xyz</p>
        <p>xyz</p>
        <p>xyz</p>
        <author>abc</author>
      </div>
      <div>
        <p>xyz</p>
        <p>xyz</p>
        <p>xyz</p>
        <author>abc</author>
      </div>
    </text>
</entry>

我试过这个解决方案:

<xsl:template match="entry">
    <entry>
       <text>
         <div>
           <xsl:apply-templates select="child::node()[not(preceding-sibling::author)]"/>
         </div>
       </text>
    </entry>
</xsl:template>

这适用于第一组&lt;p&gt; + &lt;author&gt;,但不适用于下一组。

我将不胜感激。

【问题讨论】:

标签: xslt


【解决方案1】:

您可以在作者 (preceding-sibling:*) 之前将所有不是作者 (name() != 'author') 的元素分组,并将当前作者作为下一个后续作者 (generate-id( following-sibling::author[1]) = generate-id(current())):

preceding-sibling::*[ name() != 'author' and
   generate-id( following-sibling::author[1]) = generate-id(current()) ]

试试这样的:

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:strip-space elements="*" />
    <xsl:output method="xml" indent="yes"/>


    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="text">
        <xsl:copy>
            <xsl:apply-templates select="author" mode="adddiv"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="author" mode="adddiv" >
        <!-- preceding siblings not  author   -->
        <xsl:variable name="fs" select="preceding-sibling::*[ name() != 'author' and
                                             generate-id( following-sibling::author[1]
                                          ) = generate-id(current()) ]" />

        <div >
            <xsl:apply-templates select="$fs | ." />
        </div>
    </xsl:template>
</xsl:stylesheet>

这将生成以下输出:

<entry>
  <text>
    <div>
      <p>xyz</p>
      <p>xyz</p>
      <p>xyz</p>
      <p>xyz</p>
      <author>abc</author>
    </div>
    <div>
      <p>xyz</p>
      <p>xyz</p>
      <p>xyz</p>
      <author>abc</author>
    </div>
  </text>
</entry>

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2021-12-05
    • 2014-06-10
    • 1970-01-01
    • 2018-04-20
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多