第一个匹配的祖先,名字



Hello XPath/Xslt Friends,

我有以下 Xml。我想确定 cout 元素的第一个匹配部分或章节的 id。如果cout最近的节点是章节,那么我将获得章节 ID,否则是节 ID。

<book>
    <chapter id="chapter1">
        <aa>
            <cout></cout> --> i will get "chapter1"
        </aa>
        <section id="section1">
            <a>
                <b>
                    <cout></cout> --> i will get section1
                </b>
            </a>
        </section>
        <section id="section2">
            <a>
                <b>
                    <cout></cout> --> i will get section2
                </b>
            </a>
        </section>
    </chapter>
</book>

我尝试了以下语句:

<xsl:value-of select="ancestor::*[local-name() = 'section' or local-name() = 'chapter']/@id" />

但是在第 1 节中包含的cout的情况下,它将给我第 1 章,而不是第 1 节。有什么解决办法吗?

您当前的语句是选择名称为 sectionchapter 的所有祖先,选择后,xsl:value-of 将仅按文档顺序返回第一个祖先的值(在 XSLT 1.0 中(。

试试这个

<xsl:value-of select="ancestor::*[local-name() = 'section' or local-name() = 'chapter'][1]/@id" />

如果cout没有祖先section,则打印chapter ID否则打印section ID。

<xsl:for-each select="//cout">
          <xsl:if test="count(ancestor::section)= 0">
               <xsl:value-of select="ancestor::chapter/@id"/>
          </xsl:if>
          <xsl:if test="count(ancestor::section)>0">
              <xsl:value-of select="ancestor::section/@id"/>
          </xsl:if>
</xsl:for-each>

最新更新