« back

I Do Declare! Instruct Builder to Create XML

21 Nov 2012

Next time you want to spend an hour and a half tracking down a bug, just do this and you'll be all set!

So today a fellow apprentice and I were working on a script to pull some info from a database and parse XML. For a while, it was more like XM-HELL. We were using builder and took a cue from the documentation on the Builder site.

 1     require 'rubygems'
 2     require_gem 'builder'
 3 
 4     builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2)
 5     builder.person { |b| b.name("Jim"); b.phone("555-1234") }
 6     #
 7     # Prints:
 8     # <person>
 9     #   <name>Jim</name>
10     #   <phone>555-1234</phone>
11     # </person>

We had our target set to STDOUT but realized that we would probably need to save the XML to a file so we changed our target to a file. We would open up the file and be able to see all the info we needed. Great. Enter Nokogiri. We wanted to use Nokogiri for testing and when we were having it read our file, we were getting "". We could see that we had a Nokogiri object, and that our file looked right so what was wrong? To the internets! No Dice. 1.5 hrs with no avail, we reached out for help.

It turns out that as Nokogiri failed silently, the real problem was that we had no XML declaration being written to our file. So even though Nokogiri was reading our file, it did not recognize it as what we thought it was. Turns out that 1. We actually didn't need to save to a file for our project specification. 2. If you did need to save it to a file, you could fix that issue with this...

1     xml.instruct!
2         #=> <?xml version="1.0" encoding="UTF-8"?>
3     xml.instruct! :aaa, :bbb=>"ccc"
4         #=> <?aaa bbb="ccc"?>

Woo-Hoo!!!!

comments powered by Disqus