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?
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.
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.
The current node can be accessed as current() within XPath predicates.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With