XSLT 2.0 使用 for-each-group

XSLT 2.0 Using for-each-group

我目前正在尝试将一个非常混乱的部分 xml 转换为更具可读性的内容,但是当我的代码没有产生我想要的内容时。

我能否得到一些关于我的代码有什么问题的反馈,以及我该如何修复它?

示例输入:

<root>
 <body>
   <para>
    <heading> name </heading>
   </para>
   <para> This is the name </para>
   <para>
    <heading> Usage </heading>
   </para>
   <para> This is the usage </para>
 </body>
<root>

我希望看到的输出是:

<root>
 <conbody>
  <section>
   <title> Name </title>
   <p> This is the name </p>
  </section>
  <section>
   <title> Usage </title>
   <p> This is the usage </p>
 <conbody>
<root>

我的代码目前是这样的:

<xsl:template match="body">
    <conbody>
        <xsl:for-each-group select="para" group-starting-with="para[heading]">
            <section>
                <title>
                    <xsl:apply-templates select="element()"/>
                </title>
                <p>
                    <xsl:apply-templates select="*"/>
                </p>
            </section>
        </xsl:for-each-group>
    </conbody>
</xsl:template>

内容没有被正确复制,我不确定为什么?

这是因为您需要将模板应用到 current-group()

您可以尝试在第一个 xsl:apply-templates 中使用 current-group()[1],在第二个 xsl:apply-templates 中使用 current-group()[not(position()=1)];这应该让你接近。

下面是创建 titlep 元素的方法略有不同的示例...

XML 输入

<root>
    <body>
        <para>
            <heading> name </heading>
        </para>
        <para> This is the name </para>
        <para>
            <heading> Usage </heading>
        </para>
        <para> This is the usage </para>
    </body>
</root>

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="body">
    <conbody>
      <xsl:for-each-group select="para" group-starting-with="para[heading]">
        <section>
          <xsl:apply-templates select="current-group()"/>
        </section>
      </xsl:for-each-group>
    </conbody>
  </xsl:template>

  <xsl:template match="para">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="para/text()">
    <p><xsl:value-of select="."/></p>
  </xsl:template>

  <xsl:template match="heading">
    <title><xsl:apply-templates/></title>
  </xsl:template>

</xsl:stylesheet>

XML输出

<root>
   <conbody>
      <section>
         <title> name </title>
         <p> This is the name </p>
      </section>
      <section>
         <title> Usage </title>
         <p> This is the usage </p>
      </section>
   </conbody>
</root>