使用java中的dom解析器将xml文件转换为json对象 [英] Convert xml file to json object using dom parser in java

查看:40
本文介绍了使用java中的dom解析器将xml文件转换为json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将任何类型的 XML 文件转换为 JSON 对象结构.不同的 xml 文件具有不同深度的元素和子元素.当同名元素处于相同高度时创建数组我需要一个递归函数来为任何结构化的 XML 文件创建精确的 JSON 对象

Trying to convert any type of XML file to JSON object structure . Different xml files are having varied depths of elements and sub-elements. creation of arrays when elements with same name are at same height I need a recursive function which create exact JSON Object for any structured XML file

推荐答案

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author nikunj.m
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class xmlTojsonDom1 {

public static void main(String[] args) {
    try {
        File file = new File("D:/Noname1.xml");
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = dBuilder.parse(file);
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        if (doc.hasChildNodes()) {
            JSONArray ddd = printNote_1(doc.getChildNodes());
            System.out.println("ddd ::::: " + ddd);
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

private static JSONArray printNote_1(NodeList nodeList) {
    JSONArray dataArr = new JSONArray();
    JSONObject dataObject = new JSONObject();
    for (int count = 0; count < nodeList.getLength(); count++) {
        Node tempNode = nodeList.item(count);
        if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
            if (tempNode.hasChildNodes() && tempNode.getChildNodes().getLength() > 1) {
                JSONArray temArr = printNote_1(tempNode.getChildNodes());
                if (dataObject.containsKey(tempNode.getNodeName())) {
                    dataObject.getJSONArray(tempNode.getNodeName()).add(temArr.getJSONObject(0));
                } else {
                    dataObject.put(tempNode.getNodeName(), temArr);
                }
            } else {
                dataObject.put(tempNode.getNodeName(), tempNode.getTextContent());
            }
        }
    }
    dataArr.add(dataObject);
    return dataArr;
}

}

这篇关于使用java中的dom解析器将xml文件转换为json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆