Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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?

like image 206
Sabrina Avatar asked Aug 25 '10 20:08

Sabrina


People also ask

Can you use XPath expression used to select the target node and its values?

XPath assertion uses XPath expression to select the target node and its values. It compares the result of an XPath expression to an expected value. XPath is an XML query language for selecting nodes from an XML. Step 1 − After clicking Add Assertion, select Assertion Category – Property Content.

What does XPath return?

XPath return valuesa float, when the XPath expression has a numeric result (integer or float) a 'smart' string (as described below), when the XPath expression has a string result. a list of items, when the XPath expression has a list as result.

Which XPath expression is used to match the current node?

The current node can be accessed as current() within XPath predicates.


1 Answers

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.

like image 116
John Kugelman Avatar answered Sep 20 '22 23:09

John Kugelman