title: Using Ruby loops to parse an XML doc
body: <p>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.</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  &lt;RandomTag&gt;
      &lt;library name='Favorite Books'&gt;
          &lt;book ISBN="11342343"&gt;
            &lt;title&gt;TKAM&lt;/title&gt;
            &lt;description&gt;Desc1&lt;/description&gt;
            &lt;author&gt;H Lee&lt;/author&gt;
          &lt;/book&gt;
          &lt;book ISBN="989894781234"&gt;
            &lt;title&gt;Catcher in the Rye&lt;/title&gt;
            &lt;description&gt;Desc2&lt;/description&gt;
            &lt;author&gt;JD S&lt;/author&gt;
          &lt;/book&gt;
      &lt;/library&gt;
      &lt;library name='Other Books'&gt;
          &lt;book ISBN="123456789"&gt;
            &lt;title&gt;Murphy\'s Gambit&lt;/title&gt;
            &lt;description&gt;Desc3&lt;/description&gt;
            &lt;author&gt;Syne M&lt;/author&gt;
          &lt;/book&gt;
      &lt;/library&gt;
  &lt;/RandomTag&gt;
  </code></pre>
  
  <p>I'm using a loop similar to the following to iterate through:</p>
  
  <pre><code>f = File.open(args[:file])
  doc = Nokogiri::XML(f)
  f.close
  
  doc.css('library').each do |node|
    children = node.children
    lib = {"name" =&gt; node['name']}
    Library.create(lib)
  
    doc.css('book').each do |n|
      churn = n.children
      book = {#book elements}
      Book.create(book)
    end
  end
  </code></pre>
  
  <p>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.</p>
  
  <p>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?</p>