将 XML 解析为 JSON

Parsing XML into JSON(将 XML 解析为 JSON)
本文介绍了将 XML 解析为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 XML 文件,比如

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

如何将其解析为 JSON 结构文件?

How can I parse this into JSON structure file?

推荐答案

对于一个简单的解决方案,我推荐 Jackson,一个 Java 库生成和读取带有 XML 扩展的 JSON,因为它可以通过几行简单的代码将任意复杂的 XML 转换为 JSON.

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>

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.

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.

这篇关于将 XML 解析为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)