Sabrina Sabrina - 1 month ago 7
Ruby Question

Using XPath on single node returns elements in all nodes

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.spath("//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?

Answer

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.