在java中使用dom解析器将xml文件转换为json对象
尝试将任何类型的XML文件转换为JSON对象结构。 不同的xml文件具有不同深度的元素和子元素。 当同名元素处于相同高度时创建数组 我需要一个递归函数,它可以为任何结构化XML文件创建精确的JSON对象/*在java中使用dom解析器将xml文件转换为json对象,java,xml,jsonobject,Java,Xml,Jsonobject,尝试将任何类型的XML文件转换为JSON对象结构。 不同的xml文件具有不同深度的元素和子元素。 当同名元素处于相同高度时创建数组 我需要一个递归函数,它可以为任何结构化XML文件创建精确的JSON对象/* /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author nikunj.m */ import java.io
/*
* 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;
}
*要更改此模板,请选择工具|模板
*然后在编辑器中打开模板。
*/
/**
*
*@作者nikunj.m
*/
导入java.io.File;
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入net.sf.json.JSONArray;
导入net.sf.json.JSONObject;
导入org.w3c.dom.Document;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
公共类xmlTojsonDom1{
公共静态void main(字符串[]args){
试一试{
File File=新文件(“D:/Noname1.xml”);
DocumentBuilder dBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=dBuilder.parse(文件);
System.out.println(“根元素:+doc.getDocumentElement().getNodeName());
if(doc.hasChildNodes()){
JSONArray ddd=printNote_1(doc.getChildNodes());
System.out.println(“ddd:;
}
}捕获(例外e){
System.out.println(e.getMessage());
}
}
私有静态JSONArray打印注释_1(节点列表节点列表){
JSONArray dataArr=新的JSONArray();
JSONObject dataObject=新的JSONObject();
对于(int count=0;countSystem.out.println(json) 你试过了吗????使用org.json的XML.toJSONObject()方法。是的,它可以工作,但我需要递归。您可以递归调用此方法。只要试一下,如果有任何问题,然后在下一次用代码发布问题。