如何使用xpath获取最近的祖先或祖先的孩子 [英] How to get the nearest ancestor or child of an ancestor with xpath

查看:28
本文介绍了如何使用xpath获取最近的祖先或祖先的孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看.我想要的期望输出是值为 5

Look at <bookmark/>. The desired output I want is the id with value 5

<xsl:value-of select="//bookmark/ancestor::*[@id][1]/@id"/> 只给我 4

<?xml version="1.0" encoding="UTF-8"?>
<content>
   <section id="1">
        <section id="2"/>
        <section id="3"/>
        <section id="9"/>
    </section>
    <section id="4">
        <section>
            <section id="10"/>
            <section id="5"/>
            <section>
                <bookmark/>
                <section id="6">
                    <section id="7">
                        <section id="8"/>
                    </section>
                </section>
            </section>
        </section>
    </section>
</content>

推荐答案

我理解这个问题和提供的 XML 文档的方式是,最近的 id 属性也可以发生在祖先上(section) 元素.

The way I understand the question and the provided XML document is that the nearest id attribute can also happen on an ancestor (section) element.

在任何这种情况下,使用任何 preceding:: 轴的表达式(如该问题的其他答案中所指定)不选择任何节点.

In any such case the expressions using ony the preceding:: axis (as specified in the other answers to this question) don't select any node.

选择想要的id属性的一个正确的XPath表达式是:

One correct XPath expression, which selects the wanted id attribute is:

    (//bookmark/ancestor::*[@id][1]/@id 
| 
    //bookmark/preceding::*[@id][1]/@id
     )
     [last()]

如果 bookmark 元素本身也允许使用 id 属性,则需要稍微修改上面的 XPath 表达式以适应这一点:

If the id attribute is also allowed on the bookmark element itself, the above XPath expression needs to be modified slightly to accomodate this:

    (//bookmark/ancestor-or-self::*[@id][1]/@id 
| 
    //bookmark/preceding::*[@id][1]/@id
     )
     [last()]

请注意: ancestor::preceding:: 轴不相交(不重叠).

Do note: The ancestor:: and the preceding:: axes do not intersect (do not overlap).

这篇关于如何使用xpath获取最近的祖先或祖先的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆