Using XPath on single node returns elements in all nodes

徘徊边缘 提交于 2019-12-05 08:24:50

问题


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>

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

the output looks like this:

Favorite PoemsChocolateDessertsJabberwocky
Favorite PoemsChocolateDessertsJabberwocky
Favorite PoemsChocolateDessertsJabberwocky

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?


回答1:


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.




回答2:


Remove the // from the title xpath expression.



来源:https://stackoverflow.com/questions/3569966/using-xpath-on-single-node-returns-elements-in-all-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!