tags:

views:

77

answers:

4

Hi, everyone,

I want to convert the XML file to the JSON format, but I don't know how to convert it into JSON format. Can anyone help me? Thank you.

<class>
    <num>2</num>
    <student>
        <name>[email protected]</name>
        <age>5</age>
    </student>
    <student>
        <name>[email protected]</name>
        <age>10</age>
    </student>
</class>

Update: sorry to everyone I don't mention it clearly

I just want to JSON format of the above XML file. And it is not done by any program. The answer will like the

{
  "class"

...

}
+2  A: 

If you're using java, I would say go with json-lib.

InputStream in = ConvertXMLtoJSON.class.getResourceAsStream("file.xml");
String xml = IOUtils.toString(in);

XMLSerializer xmlSerializer = new XMLSerializer(); 
JSON json = xmlSerializer.read(xml);  
System.out.println(json.toString(2));
Banang
@Banang, thank you for your reply.
Questions
No worries, glad I could help.
Banang
+1  A: 

You can use an XSLT stylesheet to convert XML to basically anything, including JSON, check out XML2JSON-XSLT at Google Code, which is an XSLT stylesheet which has already been made which will do it for you. Using XSLT will allow you to serve XML which will be read as JSON by the browser. It would be smart to do the transformation on the server-side if you are serving the JSON to Ajax applications.

Andrew Dunn
@Andrew Dunn, thank you for your reply.
Questions
+1  A: 

I am writing this answer assuming you are interested in JSON representation itself of given XML and not in how you convert it.

Exact representation:

{num:2, student:{name:"[email protected]", age:5}, student:{name:"[email protected]", age:10}}

But I think you should define a member as array of Student. Which will result in:

{num:2, students:[{name:"[email protected]", age:5}, {name:"[email protected]", age:10}]}
Hemant
+1  A: 

If you're using PHP, you might want to look at the built-in JSON functions:

http://www.php.net/json

In particular, json_encode will turn a PHP array into a JSON string, so if you can convert your XML into an array first (xml_parse_into_struct may do what you want, there are plenty of third party libraries too) you should be able to go from XML to JSON in two steps.