获得第一个前兄弟和应用模板

时间:2014-01-09 09:07:20

标签: xslt

我有以下XML代码

<root>
<title num="1/2"><content-style font-style="bold">Application</content-style> (O 1 r 2)</title>
<para><content-style font-style="bold">2.</content-style>—(1) Subject to paragraph (2), these Rules apply to all proceedings in-</para>
<para>(2) These Rules do not have effect in relation to proceedings in respect of which rules have been or may be made under any written law for the specific purpose of such proceedings or in relation to any criminal proceedings.</para>
<para>(3) Where prior to the coming into operation of these Rules, reference is made in any written law to any Rules of Court that reference shall be to these Rules.</para>
</root>

以及下面的XSLT

<xsl:template name="para" match="para">
  <xsl:choose>
    <xsl:when test="./@align">
      <div class="para align-{@align}">
        <xsl:apply-templates/>
      </div>
    </xsl:when>
    <xsl:otherwise>

      <xsl:choose>
        <xsl:when test="preceding-sibling::title[1]/@num[1]">
          <xsl:apply-templates/>
        </xsl:when>
        <xsl:otherwise>
          <div class="para">
            <xsl:apply-templates/>
          </div>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:otherwise>
  </xsl:choose>

</xsl:template>

这里当我试图运行此<xsl:when test="preceding-sibling::title[1]/@num[1]">时没有按预期工作。对于第一个para模板应该直接应用,对于第二个和第三个模块,首先应该有一个<div class="para">并且在其中应该应用模板(否则条件),但是在我的所有段<xsl:when test="preceding-sibling::title[1]/@num[1]">的案例都得到满足,它直接应用模板。请告诉我哪里出错了。

由于

2 个答案:

答案 0 :(得分:3)

preceding-sibling::*轴匹配所有前面的兄弟,而不仅仅是直接兄弟,因此您首先必须选择直接兄弟,然后检查它是否是title元素:

preceding-sibling::*[1]/self::title

我建议使用更多的XSLT-ish方法,并用更具体的模板替换嵌套的<xsl:choose>

<xsl:template match="para[@align]" priority="2">
  <div class="para align-{@align}">
    <xsl:apply-templates/>
  </div>
</xsl:template>

<xsl:template match="para[preceding-sibling::*[1]/self::title/@num]" priority="1">
  <xsl:apply-templates/>
</xsl:template>

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

如果您坚持使用<xsl:choose>,请只使用一个:

<xsl:template match="para">
  <xsl:choose>
    <xsl:when test="./@align">
      <div class="para align-{@align}">
        <xsl:apply-templates/>
      </div>
    </xsl:when>
    <xsl:when test="preceding-sibling::*[1]/self::title/@num">
      <xsl:apply-templates/>
    </xsl:when>
    <xsl:otherwise>
      <div class="para">
        <xsl:apply-templates/>
      </div>
    </xsl:otherwise>
  </xsl:choose>    
</xsl:template>

答案 1 :(得分:2)

尝试替换

<xsl:when test="preceding-sibling::title[1]/@num[1]">

<xsl:when test="preceding-sibling::*[1][name()='title']/@num">
相关问题