Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML into JSON

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?

like image 768
SPG Avatar asked Jul 19 '11 10:07

SPG


1 Answers

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.

like image 168
Programmer Bruce Avatar answered Oct 02 '22 20:10

Programmer Bruce