views:

133

answers:

4

I am trying to generate some JSON from an XML file, but not a straightforward conversion. I wish to pick and choose bits and have a slightly different structure.

I would rather not just concatenate a giant string together and was wondering if there were some decent libraries around to do this.

Also, for testing I would like to be able to validate the created json, just a simple check to see if it is valid JSON

+1  A: 

Load the XML into a set of classes (use XMLSerializer) then implement JSON generator methods on those classes. Different methods, different JSON.

AZ
+1  A: 

You can convert XML to other text representations pretty easily using XSLT, particularly file-to-file using xsltproc or a command-line version of xalan.

XSLT is sometimes an awkward programming language, but if you go this route, I have two recommendations for JSON conversions. Set your output to text, with a UTF-8 character set:

<xsl:output method="text" encoding="UTF-8" />

and run JSLint on the result, in order to catch any bugs in your XSLT file.

system PAUSE
Yeah, I have used XSLT to achieve this in the past, but arent XSLT's quite slow? I need this to be pretty nippy.
qui
+1  A: 

I would probably use Linq to XML (XElement and friends) to generate the new object and then pass that object to the Json serializer.

timvw
A: 

Other answers look good: I think I would also bind source format into objects, then serialize as the other formats. And any transformations would be done to objects, and not using data format representation. When using proper parser (for input) and generators/serializers (for output), you do not have to worry about well-formedness (resulting xml or json being syntactically correct). And for biz-logic validity you could (and should) do it using objects.

StaxMan