Convert the XML to JSON format
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>example1@email.com</name>
<age>5</age>
</student>
<student>
<name>example2@email.com</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"
...
}
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));
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.
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.
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:"example1@email.com", age:5}, student:{name:"example2@email.com", age:10}}
But I think you should define a member as array of Student. Which will result in:
{num:2, students:[{name:"example1@email.com", age:5}, {name:"example2@email.com", age:10}]}
精彩评论