您的位置:首页 > 编程语言 > Java开发

JAVA XML转JSON简单实现(dom4j)

2017-10-25 15:27 309 查看
package com.xwtech.app.util;

import java.io.File;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

public class XMLJSONUtil {

/**

* 把Element对象转JSON对象(适用能转JSON的XML)

* @param node

* @return

*/

public static JSONObject XMLToJSON(Element node){

JSONObject jsonObj = new JSONObject();

XMLToJSON(node, jsonObj);

return jsonObj;

}

/**
* XML转JSON步骤
* @param node
* @param jsonObj
* @author YJ
*/
private static void XMLToJSON(Element node,JSONObject jsonObj){
List<Element> listElement = node.elements();//所有一级子节点的list
if (listElement == null || listElement.size() == 0){
jsonObj.put(node.getName(), node.getTextTrim());
return;
}
Boolean isJSONArray = false;
JSONArray jsonArray = new JSONArray();
//简单判断该子节点是否需要用JSONArray对象转
if (listElement.size() > 1 &&
listElement.get(0).getName().equals(listElement.get(1).getName())){
isJSONArray = true;
jsonObj.put(node.getName(), jsonArray);
}
for (Element ele : listElement){//遍历所有一级子节点
if (isJSONArray){
JSONObject jsonObject = new JSONObject();
jsonArray.add(jsonObject);
XMLToJSON(ele, jsonObject);
}else{
JSONObject jsonObject = new JSONObject();
XMLToJSON(ele, jsonObj);
}

}
}

/**
* 读取文本XMl字符串获取Document对象
* @param File (文本路径)(如:"D:\\a.xml")
* @return
* @throws Exception
*/
public static Document getDocumentByReadText(String File)throws Exception{
try{
SAXReader sax=new SAXReader();//创建一个SAXReader对象
sax.setEncoding("UTF-8");
File xmlFile=new File(File);//根据指定的路径创建file对象
Document document=sax.read(xmlFile);//获取document对象,如果文档无节点,则会抛出Exception提前结束
return  document;
}catch(Exception e){
SAXReader sax=new SAXReader();//创建一个SAXReader对象
sax.setEncoding("GBK");
File xmlFile=new File(File);//根据指定的路径创建file对象
Document document=sax.read(xmlFile);//获取document对象,如果文档无节点,则会抛出Exception提前结束
return  document;
}
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java xml json