views:

98

answers:

2

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?

TIA!

+2  A: 

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.

John Kugelman
aha! Thank you very much. So it doesn't matter that I am applying the xpath expression to a node?
Sabrina
Putting `/` or `//` at the front makes the XPath an absolute path. When you use those the XPath evaluator ignores the context node and starts at the document root.
John Kugelman
A: 

Remove the // from the title xpath expression.

John Drummond