开发者

Parsing XML into JSON

开发者 https://www.devze.com 2023-03-21 02:19 出处:网络
I have an XML file, like <stock><name>AXL</name><time>19-07</time><price>11.34</price></stock>

I have an XML file, like

<stock><name>AXL</name><time>19-07</time><price>11.34</price></stock>
开发者_如何转开发<stock><name>AIK</name><time>19-07</time><price>13.54</price></stock>
<stock><name>ALO</name><time>19-07</time><price>16.32</price></stock>
<stock><name>APO</name><time>19-07</time><price>13.56</price></stock>
...............more

How can I parse this into JSON structure file?


For a simple solution, I recommend Jackson, a Java library for generating and reading JSON with an extension for XML, as it can transform arbitrarily complex XML into JSON with just a few simple lines of code.

input.xml

<entries>
  <stock><name>AXL</name><time>19-07</time><price>11.34</price></stock>
  <stock><name>AIK</name><time>19-07</time><price>13.54</price></stock>
  <stock><name>ALO</name><time>19-07</time><price>16.32</price></stock>
  <stock><name>APO</name><time>19-07</time><price>13.56</price></stock>
</entries>

The Java Code:

import java.io.File;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

import com.fasterxml.jackson.xml.XmlMapper;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    XmlMapper xmlMapper = new XmlMapper();
    List entries = xmlMapper.readValue(new File("input.xml"), List.class);

    ObjectMapper jsonMapper = new ObjectMapper();
    String json = jsonMapper.writeValueAsString(entries);
    System.out.println(json);
    // [{"name":"AXL","time":"19-07","price":"11.34"},{"name":"AIK","time":"19-07","price":"13.54"},{"name":"ALO","time":"19-07","price":"16.32"},{"name":"APO","time":"19-07","price":"13.56"}]
  }
}

This demo uses Jackson 1.7.7 (the newer 1.7.8 should also work), Jackson XML Databind 0.5.3 (not yet compatible with Jackson 1.8), and Stax2 3.1.1.


http://keithchadwick.wordpress.com/2009/03/14/converting-xml-to-json-with-xsl-part-2/

You haven't specified language... so... I haven't got more specific on it than to think "you already have XML, probably you have access to xsl/xslt":

http://www.w3.org/TR/xslt

http://www.thomasfrank.se/xml_to_json.html

0

精彩评论

暂无评论...
验证码 换一张
取 消