我有一个XML文件,例如
<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
如何将其解析为JSON结构文件?
对于一个简单的解决方案,我建议使用Jackson库,它是一个Java库,用于生成和读取带有XML扩展名的JSON,因为它只需几行简单的代码就可以将任意复杂的XML转换为JSON。
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>
Java代码:
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"}] } }
该演示使用Jackson 1.7.7(较新的1.7.8也可以使用),Jackson XML Databind 0.5.3(尚未与Jackson 1.8兼容)和Stax2 3.1.1。