xpath 使用//和后代或自我和自我 [英] xpath using // and descendant-or-self and self

查看:35
本文介绍了xpath 使用//和后代或自我和自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得与哈利波特同年的所有书名

I am trying to get all book title with same year as Harry Potter

"/bookstore/book[year=//descendant-or-self::book[title='Harry Potter']/year]/title"

正确输出与书名为哈利波特"的书同年的所有书名

yield all books title with same year as book titled 'harry potter' correctly

"/bookstore/book[year=descendant-or-self::book[title='Harry Potter']/year]/title";

只生产名为哈利波特"的书

yield only books titled 'harry potter'

虽然,最初我做到了:

"/bookstore/book[year=self::book[title='Harry Potter']/year]/title";

只生产名为哈利波特"的书.

yield only books titled 'harry potter' as well.

XML 文档来自:http://www.w3schools.com/xml/xml_xpath.asp

为什么最后两个没有产生我想要的所有结果,而只有书本身?

Why the last two not yield all the results I want but only the book itself?

推荐答案

首先,对于所有实际目的,//descendant-or-self::book 的含义与 //相同book,所以你的第一个表达是正确的,但不必要的冗长.

Firstly, for all practical purposes, //descendant-or-self::book means the same as //book, so your first expression is correct but unnecessarily verbose.

您的第二个表达式使用 book[year=descendant-or-self::book...].在您的示例 XML 文档中,书籍没有后代书籍,因此这相当于 book[year=self::book...],这是您的第三个表达式.

Your second expression uses book[year=descendant-or-self::book...]. In your sample XML document, books do not have descendant books, so this is equivalent to book[year=self::book...], which is your third expression.

你的第三个表达式 /bookstore/book[year=self::book[title='Harry Potter']/year]/title 非常多余.如果我们去掉内部谓词,它会说

Your third expression /bookstore/book[year=self::book[title='Harry Potter']/year]/title is very redundant. If we cut out the inner predicate it's saying

/bookstore/book[year=self::book/year]/title

选择每一本书的年份与该书的年份相同 - 只要这本书有年份,这总是正确的.

which is selecting every book where the book's year is the same as the book's year - which is always true provided the book has a year.

如果你省略那个同义反复的条件,你就剩下了

If you leave out that tautological condition, you're left with

/bookstore/book[title='哈利波特']/title

它选择所有书名是'哈利波特'的书名,只能是零次或多次重复的哈利波特".

which selects the title of all books whose title is 'Harry Potter', which can only be zero or more repetitions of "Harry Potter".

基本上,您还没有理解上下文的重要性.您需要重新阅读您最喜欢的 XPath 教科书的那部分.

Basically, you haven't understood the importance of context. You need to re-read that section of your favourite XPath textbook.

这篇关于xpath 使用//和后代或自我和自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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