randombits
randombits

Reputation: 48450

XSLT equivalent for XML to JSON

I have an application where I am parsing an XML document and want to translate it into a JSON document and embed that document directly into MongoDB. Normally going from XML <-> XML I'd use a tool such as XSLT for the translation. Is there currently a decent tool to translate XML -> JSON? Only has to be uni-directional. I won't be translating it back to XML anytime soon. I just want it formatted in a particular state that's embeddable into MongoDB for retrieval and representation to a serializer in the future.

Upvotes: 0

Views: 318

Answers (2)

Jacob Brown
Jacob Brown

Reputation: 7561

If you don't mind using ActiveSupport and Ruby Hash as intermediary:

require 'active_support/core_ext'
Hash.from_xml(xml).to_json

Note that it would be pretty easy to manipulate the data when it is a Hash if you need to do so.

Also, note that converting XML to a hash can be lossy (when it comes to namespaces and attributes). If you care about this, you might check out other XML parsers (like Crack or CobraVsMongoose), or use XSLT to do the conversion.

Upvotes: 1

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

The best available tool for translating XML into JSON, either in general or for a particular vocabulary, is XSLT. Use method="text" on your xsl:output element.

Upvotes: 1

Related Questions