选择元素最后一个的属性值

时间:2015-07-31 13:51:56

标签: xml xslt xpath

我试图通过获取文档中最后@n的{​​{1}}值来显示文档中的页数。现在,我仍然得到第一个<pb/>的价值。这是我的输入xml:

<pb/>

这是我的xsl:

<p><line>While a prisoner here remains in their</line> 
            <line>so-called 1st grade, he is able to write</line> 
            <line>twice a week, in second grade once a week,</line> 
            <line>and in third grade once a month. These</line> 
            <line>grades refer to classifications that ostensibly</line>
            <line>are for conduct while here.  It is quite possible</line> 
            <line>to lose a conduct rating, as I understand it,</line> 
            <line>by not having a perpetually rusting tin cup polished</line> 
            <pb n="2"/>
            <line>brightly for daily inspection, although the tin plating long ago dis-</line>
            <line>appeared and the cup is rusty again within 2 hours after wetting.</line></p>
        <p><line>The food here is good and is well-cooked,</line> 
            <line>with one exception, the gravy, which is nothing but</line> 
            <line>flour, water, and bacon grease, Strangely enough, how-</line>
            <line>ever, no condiments, not even salt, are provided on</line> 
            <pb n="3"/>
            <line>the table, to the detriment of otherwise very good</line> 
            <line>meals.  While meat here is unrationed and is plentiful,</line> 
            <line>toilet paper; believe it or not, is rationed.  A</line> 
            <line>5¢ roll must last a prisoner 45 days, or else -- ?</line>
            <line>Perhaps, however, a prisoner can purchase additional</line> 
            <line>if it should be necessary.</line></p>

如何选择整个文档中最后<dt>Pages:</dt> <dd> <xsl:if test="//pb"> <xsl:value-of select="//pb[position()=last()]/@n"/> </xsl:if> </dd> 的{​​{1}}值?

2 个答案:

答案 0 :(得分:0)

我总是发现位置功能有点棘手,但它可能只是个人感觉。没关系,棘手的部分是position()函数使用的上下文不一定是你用来抓取节点的上下文。例如,在您的代码中,您可以选择忽略它们所在位置的所有元素。但如果他们在父母中“孤独”,他们可以匹配谓词位置()= last(),因为他们在父母中是“最后的”。

通常,我会像这样使用一些xpath(对于非常大的文档,可能在时间过程中不是最佳的):

<xsl:value-of select="//pb[not(following::pb)]/@n"/>

答案 1 :(得分:0)

您的方法存在问题:

<xsl:value-of select="//pb[position()=last()]/@n"/>

//pb[position()=last()]选择所有pb元素,这些元素是其父母 1 的最后pb个子元素。然后,您可以获取其中第一个的值。

要选择整个文档中的最后一个pb元素,您应该执行以下任一操作:

<xsl:value-of select="/descendant::pb[last()]/@n" />

或:

<xsl:value-of select="(//pb)[last()]/@n" />

当然,这只适用于格式良好的XML输入。您提供的示例不是。

-
1. http://www.w3.org/TR/xpath/#path-abbrev