在单个节点上使用XPath返回所有节点中的元素 [英] Using XPath on single node returns elements in all nodes
问题描述
我正在解析看起来像这样的XML文档:
I am parsing an XML doc that looks something like this:
<MyBook>
<title>Favorite Poems</title>
<issn>123-456</issn>
<pages>45</pages>
</MyBook>
<MyBook>
<title>Chocolate Desserts</title>
<issn>654-098</issn>
<pages>100</pages>
</MyBook>
<MyBook>
<title>Jabberwocky</title>
<issn>454-545</issn>
<pages>19</pages>
</MyBook>
我使用xpath拉出MyBook节点并像这样遍历它们:
I use xpath to pull out the MyBook nodes and iterate through them like so:
xmldoc.xpath("//MyBook").each do |node|
mytitle=node.xpath("//title").text
puts mytitle
end
输出看起来像这样:
Favorite PoemsChocolateDessertsJabberwocky
Favorite PoemsChocolateDessertsJabberwocky
Favorite PoemsChocolateDessertsJabberwocky
好像该节点实际上是整个xmldoc.但是,如果我打印出迭代器中的节点,则每次都达到我的期望时,就只有一个MyBook节点.我需要能够连续地从每个节点中拉出子节点,而不是整个文档中所有相同类型的子节点.我在做什么错了?
as if the node is really the whole xmldoc. However if I print out the node within the iterator, each time it is what I expect, just a single MyBook node. I need to be able to pull out the child nodes from each node successively, not all of the same kind of child node from the whole document. What am I doing wrong?
推荐答案
使用//title
时,它将搜索从文档根部开始的所有<title>
元素.只需使用title
查找子标题,或者使用.//title
(即使它们嵌套在其他元素中)也可以查找子标题.
When you use //title
this searches for all <title>
elements starting at the root of the document. Use either simply title
to find child titles, or .//title
if you want to find titles even if they are nested inside of other elements.
这篇关于在单个节点上使用XPath返回所有节点中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!