1

在我尝试回答问题XSLT - Tricky Transformation时,我遇到了以下任务:

对于每个标签<MMM>,计算第二 <MMM>个子标签中叶节点的数量。

将“叶节点”定义为<MMM>没有其他<MMM>标签作为子标签的标签。不过,它可能有其他标签作为子标签。

我最终得到了两个表达式:

<xsl:variable name="just_children" select="count(MMM[position() = 2 and count(MMM) = 0])"/>
<xsl:variable name="grandchildren_and_below" select="count(MMM[2]//MMM[count(MMM) = 0])"/>

第一个计算第二个孩子的叶子,第二个计算第二个孩子的所有祖先。我无法将这两个组合成一个表达式(除了我必须做的明显的求和:-))。不知何故,我无法使节点数组索引选择器[2]、附加条件count(MMM) = 0和祖先路径“//”适合同一个表达式。

那么,是否有更简洁(并且可能更优雅)的方式来编写这个表达式?

非常感谢!

对于测试,您可以使用此输入文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<MMM>
  <MMM>
    <MMM>
      <MMM/>
      <MMM/>
    </MMM>    
    <MMM>
      <MMM/>
      <MMM>
        <MMM/>
      </MMM>
    </MMM>
  </MMM>
  <MMM>
    <MMM/>
  </MMM>
</MMM>

和以下 XSLT 表:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet 
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" encoding="ISO-8859-1" indent="yes"/>

  <xsl:template match="MMM">
    <xsl:variable name="just_children" select="count(MMM[position() = 2 and count(MMM) = 0])"/>
    <xsl:variable name="grandchildren_and_below" select="count(MMM[2]//MMM[count(MMM) = 0])"/>
    <MMM just_children="{$just_children}" grandchildren_and_below="{$grandchildren_and_below}">
      <xsl:apply-templates/>
    </MMM>    
  </xsl:template>
</xsl:stylesheet>
4

1 回答 1

1

您的just_children变量可以这样写:

<xsl:variable name="just_children" select="count(MMM[2][not(MMM)])"/>

你的grandchildren_and_below变量可以这样写:

<xsl:variable name="grandchildren_and_below" select="count(MMM[2]//MMM[not(MMM)])"/>

要将它们放在一起,您可以使用后代或自我轴,就像这样

<xsl:variable name="all" select="count(MMM[2]//descendant-or-self::MMM[not(MMM)])"/>
于 2013-10-27T14:16:12.787 回答