在选择祖先名字时感到困惑

Confused in selecting ancestor name

我正在尝试使用 XSLT 打印祖先节点名称。

下面是我的 XSLT。

<xsl:apply-templates select="(//title)[1]"/>

<xsl:template match="title">
<xsl:value-of select="name(ancestor::node())"/>
</xsl:template>

而我的XML如下。

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <!--ancestor-->
    <cd>
        <!--parent-->
        <title name="titleName" property="propertyName">Empire Burlesque</title>
        <!--self-->
        <artist>Bob Dylan</artist>
        <!--following-sibling-->
        <country>USA</country>
        <!--following-sibling-->
        <company>Columbia</company>
        <!--following-sibling-->
        <price>10.90</price>
        <!--following-sibling-->
        <year>1985</year>
        <!--following-sibling-->
    </cd>
</catalog>

这里当我使用下面的语句时。

<xsl:value-of select="name(../..)"/>

否则当我使用

<xsl:value-of select="name(ancestor::node())"/>

<xsl:value-of select="name(ancestor::*)"/>

它给我下面的异常

XSLT 2.0 Debugging Error: Error: file:///C:/Users/u0138039/Desktop/Training%20Docs/XSLT%20Training/Sample.xsl:209: Wrong occurrence to match required sequence type -   Details: -     XPTY0004: The parameter value ('3' item(s)) at position '1' of the 'name' function has the wrong occurrence to match the sequence type node() ('zero or one')

但是要获取父名称,当我使用

<xsl:value-of select="name(parent::*)"/>

请告诉我为什么这适用于 parent 但不适用于 ancestor

这很令人困惑。如何使用 <xsl:value-of select="name(ancestor::node())".

之类的名称获取 ancestor 名称

谢谢

ancestor 轴包含上下文节点的 所有 个祖先:它的 parent、它的大 parent、它的 great-grandparent, 一直到根节点.

当你问一个祖先的名字时,你必须select 一个 ancestor 轴上的节点。例如:

<xsl:value-of select="name(ancestor::*[last()])"/>

将 return "catalog" 在你的例子中(注意祖先是一个反轴)。

OTOH,这个:

<xsl:value-of select="ancestor::*/name()"/>

将(在 XSLT 2.0 中)return "catalog cd" - 即 space-separated 所有节点祖先名称的列表。