【问题标题】:XML Path needed需要 XML 路径
【发布时间】:2014-06-01 03:22:10
【问题描述】:

我有以下 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
  </book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
  </book>
</bookstore>

我需要编写一个返回 2003 年之后出版的书的 XML 路径,类别是儿童,我只需要显示书的作者和标题?令人沮丧的是,除了我想念作者之外,我在 XPATH 中拥有所有写的东西。

【问题讨论】:

  • 这是我的 Xpath:/bookstore/book/title/author|/bookstore/book[@category="CHILDREN"]

标签: xml xpath


【解决方案1】:

使用以下xpath 表达式:

/bookstore/book[@category="CHILDREN" and year>2003]/*[name()="author" or name()="title"]

这里我们选择category 属性等于CHILDREN 并且year 节点值大于2003 的每一本书。 *[name()="author" or name()="title"] 有助于仅选择特定的孩子:authortitle

使用xmllint工具演示:

$ xmllint input.xml --xpath '/bookstore/book[@category="CHILDREN" and year > 2003]/*[name()="author" or name()="title"]'
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>

如果要查看authortitle 节点的值,请将/text() 添加到xpath 表达式的末尾:

$ xmllint input.xml --xpath '/bookstore/book[@category="CHILDREN" and year > 2003]/*[name()="author" or name()="title"]/text()'
Harry Potter
J K. Rowling

【讨论】:

  • 非常感谢。我尝试过类似的东西,但是我只是做了 name() ,就是这样。我试过了,它有效。再次感谢。我花了整整一周/几个小时在这上面,所以我很高兴我找到了这个网站 :)
  • 我有一个问题,我必须使用函数,否则我不会得到正确的结果?只是想看看是否有更简单的方法来获得相同的输出。
  • 无赖,我会给你一个 5 直到我点击复选标记后才看到它。这个答案绝对是5。
猜你喜欢
  • 2012-05-25
  • 2011-04-05
  • 2020-10-24
  • 1970-01-01
  • 2015-02-23
  • 2012-12-03
  • 2012-04-21
  • 2014-03-23
  • 1970-01-01
相关资源
最近更新 更多