package com.yx.emr.base.common;
import java.util.HashMap;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class XmlToJson {
/**
* 将xml转换为JSON对象
*
* @param xml xml字符串
* @return
* @throws Exception
*/
public static JSONObject xmltoJson(String xml) throws Exception {
JSONObject jsonObject = new JSONObject();
Document document = DocumentHelper.parseText(xml);
// 获取根节点元素对象
Element root = document.getRootElement();
iterateNodes(root, jsonObject);
return jsonObject;
}
/**
* 遍历元素
*
* @param node 元素
* @param json 将元素遍历完成之后放的JSON对象
*/
@SuppressWarnings("unchecked")
public static void iterateNodes(Element node, JSONObject json) {
// 获取当前元素的名称
String nodeName = node.getName();
// 判断已遍历的JSON中是否已经有了该元素的名称
if (json.containsKey(nodeName)) {
// 该元素在同级下有多个
Object Object = json.get(nodeName);
JSONArray array = null;
if (Object instanceof JSONArray) {
array = (JSONArray) Object;
} else {
array = new JSONArray();
array.add(Object);
}
// 获取该元素下所有子元素
List<Element> listElement = node.elements();