Wednesday, July 7, 2010

XML Builder

I've been using a nifty little thing called XML Builder at work lately. It takes a hash and turns it into XML. I'm using it for FusionCharts. It's actually extremely nice, demonstration:
xml = Builder::XmlMarkup.new
xml.sample(:escaped=>"This&That", :unescaped=>:"Here&There")
xml.target!  =>
  <sample escaped="This&That" unescaped="Here&There"></sample>
I got that one from this website
Basically, what I do is build a hash, say, like this:
hash = [{:label => "a label"}, {:value => "value1"}]
Then, I begin building the xml markup like so:
xml = Builder::XmlMarkup.new
xml.chart(:xAxis => "xaxis", :yAxis => "yaxis") do
  xml.label = hash[0][:label]
  xml.value = hash[1][:value]
end

This is the result:
<chart xAxis="xaxis" yAxis="yaxis">
  <label>a label</label>
  <value>value1</value>
</chart>


That little bit of xml up there fits nicely into some of those charts in Fusion Charts. With a bit of modification, it can be made to fit into any of the charts in Fusion Charts.

No comments:

Post a Comment