包含json文件转换为xml文件的词条

发布时间:2023-12-08

包含json文件转换为xml文件的词条

更新:2022-11-10 16:03

本文目录一览:

  1. java解析json,然后将其转换为xml
  2. 如何将json文件转为xml格式的文件
  3. json如何转换成xml

java解析json,然后将其转换为xml

需要的依赖:

<dependency>
    <groupId>de.odysseus.staxon</groupId>
    <artifactId>staxon</artifactId>
    <version>1.2</version>
</dependency>

代码:

public static void main(String[] args) throws Exception {
    // 输入json文件
    String encoding = "UTF-8";
    File jsonFile = new File("C:/Users/Administrator/Desktop/person.json");
    Long jsonFilelength = jsonFile.length();
    byte[] JsonBytes = new byte[jsonFilelength.intValue()];
    FileInputStream in = new FileInputStream(jsonFile);
    in.read(JsonBytes);
    in.close();
    String json = new String(JsonBytes, encoding);
    // json --> xml
    StringReader input = new StringReader(json);
    StringWriter output = new StringWriter();
    JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false)
        .repairingNamespaces(false).build();
    XMLEventReader reader = new JsonXMLInputFactory(config)
        .createXMLEventReader(input);
    XMLEventWriter writer = XMLOutputFactory.newInstance()
        .createXMLEventWriter(output);
    writer = new PrettyXMLEventWriter(writer);
    writer.add(reader);
    reader.close();
    writer.close();
    output.close();
    input.close();
    // 输出成xml文件
    File xmlFile = new File("C:/Users/Administrator/Desktop/person.xml");
    PrintWriter outFile = new PrintWriter(xmlFile);
    outFile.write(output.toString());
    outFile.flush();
    outFile.close();
}

如何将json文件转为xml格式的文件

json的话,目前比较流行的转换工具是fastjson,使用方便,速度又很快。可以在JavaBean和String型之间直接转换。 xml的话,可以采用XStream来转换。 也就是说,你可以先把json的文件内容转换成JavaBean(fastjson),然后再把JavaBean转换成xml(XStream)。

json如何转换成xml

网上都有XML和json互相转换的工具,在线就可以转换。注意XML必须有单一的根节点。

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <node>
        <id>1</id>
        <text>系统维护</text>
        <children>
            <id>user</id>
            <text>人员维护</text>
        </children>
        <children>
            <id>role</id>
            <text>角色维护</text>
            <iconCls>icon-reload</iconCls>
        </children>
    </node>
    <node>
        <text>开发维护</text>
        <children>
            <text>元数据</text>
            <state>closed</state>
            <children>
                <text>编辑样式</text>
            </children>
            <children>
                <id>dataview</id>
                <text>数据视图</text>
            </children>
        </children>
        <children>
            <text>权限资源</text>
        </children>
    </node>
</root>