If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, November 10, 2010

From XML to JSON using SAX

As a die hard Apache Cocoon user I deal with lots of XML data. And there is more then way to transform your data into another output format like xhtml.
  • use xslt to transform directly into xhtml -> serialize to xhtml -> render page
  • use xslt to transform to json -> serialize to text -> render the page template -> make an asynchronous request to fetch the json data -> preferably instantiate some javascript widget and populate it with the data
For my last project I created a new search module which was working from top-to-bottom asynchronously and fetched only the minimal amount of data at the time it was needed.

One use case was where I needed to transform a large xml document describing some tree like structure and the customer wanted that tree to be displayed nicely as a tree.

I'd like to describe how you can generically convert any xml document into json.

Let's first start taking a quick look at what JSON is all about.

You basically have to deal with arrays, objects, dates, booleans, numbers and strings.


Based on the above we can come up with a generic XML way of describing the above:









So we can easily write a generic transformer for this use case:

Now you only need to convert your input xml file into the generic JSON xml structure and transform it with the above stylesheet.

No comments:

Post a Comment