简体   繁体   English

将XML转换为JSON格式

[英]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. 我想将XML文件转换为JSON格式,但是我不知道如何将其转换为JSON格式。 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. 我只想将上述XML文件的JSON格式。 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 . 如果您使用的是Java,我会说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. 您可以使用XSLT样式表将XML转换为基本上任何东西,包括JSON,也可以在Google Code上查看XML2JSON-XSLT ,这是已经制作好的 XSLT样式表,可以为您完成。 Using XSLT will allow you to serve XML which will be read as JSON by the browser. 使用XSLT将允许您提供XML,该XML将被浏览器读取为JSON。 It would be smart to do the transformation on the server-side if you are serving the JSON to Ajax applications. 如果将JSON提供给Ajax应用程序,则在服务器端进行转换将很明智。

If you're using PHP, you might want to look at the built-in JSON functions: 如果您使用的是PHP,则可能需要查看内置的JSON函数:

http://www.php.net/json 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. 特别是,json_encode会将PHP数组转换为JSON字符串,因此,如果您可以先将XML转换为数组(xml_parse_into_struct可以满足您的要求,那么也可以使用很多第三方库),您应该可以从XML分两个步骤转换到JSON。

I am writing this answer assuming you are interested in JSON representation itself of given XML and not in how you convert it. 我正在编写此答案,假设您对给定XML的JSON表示本身感兴趣,而不对如何转换感兴趣。

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. 但是我认为您应该将成员定义为Student数组。 Which will result in: 这将导致:

{num:2, students:[{name:"example1@email.com", age:5}, {name:"example2@email.com", age:10}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM