Using Ruby loops to parse an XML doc

contpearfiac

New Member
Say I have the following XML doc. I'm using Ruby 1.9.3, Rails 3.2.6, and Nokogiri 1.5.5 to parse the XML into a database. I want to be able to loop through the XML tags and pick out elements in the correct order.\[code\]<?xml version="1.0"?><RandomTag> <library name='Favorite Books'> <book ISBN="11342343"> <title>TKAM</title> <description>Desc1</description> <author>H Lee</author> </book> <book ISBN="989894781234"> <title>Catcher in the Rye</title> <description>Desc2</description> <author>JD S</author> </book> </library> <library name='Other Books'> <book ISBN="123456789"> <title>Murphy\'s Gambit</title> <description>Desc3</description> <author>Syne M</author> </book> </library></RandomTag>\[/code\]I'm using a loop similar to the following to iterate through:\[code\]f = File.open(args[:file])doc = Nokogiri::XML(f)f.closedoc.css('library').each do |node| children = node.children lib = {"name" => node['name']} Library.create(lib) doc.css('book').each do |n| churn = n.children book = {#book elements} Book.create(book) endend\[/code\]So I'm basically searching for a library, and then once I find it, I'm searching for all books within that library. The problem with my current code is that the .css() method searches until EOF. So the inner 'book' loop hits on every single book, regardless of which library it resides in. Additionally, once I hit a second library, the 'book' loop again starts from beginning of the doc and continues through every book. End result is I get the correct number of libraries with the right name, but every library has every book. I need a way to stop searching for books (break from the inner loop) when I hit a new 'library' tag.Is there a different method than .css() that will do this? Is there some way to write in a break statement in my loop to exit upon a given situation?
 
Back
Top