XPath max 函数和括号的使用 [英] XPath max function and the use of brackets

查看:63
本文介绍了XPath max 函数和括号的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下 XML:

Let's say we have the following XML:

<people>
  <student name="Peter">
    <subject>
      <name>English</name>
      <grade>60</grade>
    </subject>
    <subject>
      <name>Programming</name>
      <grade>70</grade>
    </subject>
    <diploma>80</diploma>
  </student>
</people>

我们试图找到的是科目"的名称",其中Peter"在Grade"中的数字最大.整个 XML 还有几个名字不同的人,但我认为这并不重要.这一切都遵循相同的原则.

What we're trying to find is the "name" of the "subject" where "Peter" has the largest number in "Grade". The entire XML has a few more people with different names but I dont think that matters. It all follows the same principle.

这个 XPath 怎么会失败:

How come this XPath fails:

people/student[@name="Peter"][max(subject/grade)]/subject/name

错误被称为:

NO MATCH!

如果在计算最大值后必须打印出不同的值,我就无法正确使用 max 函数.

I've never been able to use the max function correctly if I had to print out a different value after calculating the maximum value.

我还花了很多时间在 XMLLINT 上尝试使其在 Xpath1.0 中工作

I've also spent quite a few minutes on XMLLINT trying to make it work in Xpath1.0

xmllint --xpath 'people/student[name='Peter'][not(subject/grade > subject/grade)]/subject/grade' grades.xml >result.txt

返回:

XPath set is empty

我已经阅读了这些函数,所以我很欣赏代码示例而不是文档链接.如果您发现 XML 错误,则可能是我手动将其翻译成英文时出现问题.

I've read up on the functions, so I would appreciate code examples and not links to documentations. If you find an XML error there's probably been an issue when I was manually translating this into english.

people/student[@name="Peter"]/max(subject/grade)

工作正常并输出正确的最大值.这让我相信问题出在我对 [] 的使用上.

Worked fine and outputted the correct maximum value. Which leads me to believe the problem is with my usage of [] .

推荐答案

您对 max() 的使用不起作用,因为您没有将 max() 与任何东西进行比较.

Your use of max() didn't work because you aren't comparing max() to anything.

这里有几个选项...

XPath 2.0

/people/student[@name="Peter"]/subject[grade = max(../subject/grade)]/name

XPath 1.0

/people/student[@name="Peter"]/subject[not(preceding-sibling::subject/grade > grade) and not(following-sibling::subject/grade > grade)]/name

请注意,xmllint 仅支持 XPath 1.0.

Note that xmllint only supports XPath 1.0.

这篇关于XPath max 函数和括号的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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