获取子节点包含属性的节点 [英] Get nodes where child node contains an attribute
问题描述
假设我有以下 XML:
Suppose I have the following XML:
<book category="CLASSICS">
<title lang="it">Purgatorio</title>
<author>Dante Alighieri</author>
<year>1308</year>
<price>30.00</price>
</book>
<book category="CLASSICS">
<title lang="it">Inferno</title>
<author>Dante Alighieri</author>
<year>1308</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>
我想做一个 xpath 来取回所有具有标题节点且语言属性为it"的书籍节点.
I would like to do an xpath that gets back all book nodes that have a title node with a language attribute of "it".
我的尝试看起来像这样:
My attempt looked something like this:
//book[title[@lang='it']]
但这没有用.我希望取回节点:
But that didn't work. I expect to get back the nodes:
<book category="CLASSICS">
<title lang="it">Purgatorio</title>
<author>Dante Alighieri</author>
<year>1308</year>
<price>30.00</price>
</book>
<book category="CLASSICS">
<title lang="it">Inferno</title>
<author>Dante Alighieri</author>
<year>1308</year>
<price>30.00</price>
</book>
有什么提示吗?
推荐答案
尝试
//book[title/@lang = 'it']
内容如下:
- 获取所有
book
元素- 至少有一个
title
- 有一个属性
lang
- 值为
"it"
您可能会发现 this 很有帮助 — 这是一篇名为 五段中的 XPath" 作者:Ronald Bourret.
You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.
但老实说,
//book[title[@lang='it']]
和上面的应该是等价的,除非您的 XPath 引擎有问题".因此,它可能是您没有向我们展示的代码或示例 XML 中的某些内容——例如,您的示例是一个 XML 片段.是否可能是根元素有一个命名空间,而您没有在查询中计算它?你只告诉我们它没有用,但你没有告诉我们你得到了什么结果.But in all honesty,
//book[title[@lang='it']]
and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.这篇关于获取子节点包含属性的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 值为
- 有一个属性
- 至少有一个