gpt4 book ai didi

java - 将 XML 解析为 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:22 26 4
gpt4 key购买 nike

我有一个 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 ,一个用于生成和读取带有 XML 扩展的 JSON 的 Java 库,因为它只需几行简单的代码就可以将任意复杂的 XML 转换为 JSON。

输入.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 .

关于java - 将 XML 解析为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6746059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com