1、所需jar包
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b3e78ba5a386949f969b89db6818acae.png)
2、工具类具体代码
package test;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* xml工具类
* @author sleep
* @date 2016-09-13
*/
public class XmlTools {
/**
* String 转 org.dom4j.Document
* @param xml
* @return
* @throws DocumentException
*/
public static Document strToDocument(String xml) throws DocumentException {
return DocumentHelper.parseText(xml);
}
/**
* org.dom4j.Document 转 com.alibaba.fastjson.JSONObject
* @param xml
* @return
* @throws DocumentException
*/
public static JSONObject documentToJSONObject(String xml) throws DocumentException {
return elementToJSONObject(strToDocument(xml).getRootElement());
}
/**
* org.dom4j.Element 转 com.alibaba.fastjson.JSONObject
* @param node
* @return
*/
public static JSONObject elementToJSONObject(Element node) {
JSONObject result = new JSONObject();
// 当前节点的名称、文本内容和属性
List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的list
for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
result.put(attr.getName(), attr.getValue());
}
// 递归遍历当前节点所有的子节点
List<Element> listElement = node.elements();// 所有一级子节点的list
if (!listElement.isEmpty()) {
for (Element e : listElement) {// 遍历所有一级子节点
if (e.attributes().isEmpty() && e.elements().isEmpty()) // 判断一级节点是否有属性和子节点
result.put(e.getName(), e.getTextTrim());// 沒有则将当前节点作为上级节点的属性对待
else {
if (!result.containsKey(e.getName())) // 判断父节点是否存在该一级节点名称的属性
result.put(e.getName(), new JSONArray());// 没有则创建
((JSONArray) result.get(e.getName())).add(elementToJSONObject(e));// 将该一级节点放入该节点名称的属性对应的值中
}
}
}
return result;
}
}
3、测试用的xml报文数据 这里不做换行处理了
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><CONTENT><ORDER_ID>BX202007141625490000041132</ORDER_ID><PNR_CODE>JW56FV</PNR_CODE><RETCODE>BIABX0000</RETCODE><RETMEMO>success:1 fail:0</RETMEMO><RETURNINFOS><RETURNINFO><INSURNAME>NAITO/SHIMPEI</INSURNAME><TICKETNO>7814803739892</TICKETNO><FLIGHTNO>MU9331</FLIGHTNO><FLAG>success</FLAG><DETAILMEMO>TEST4</DETAILMEMO></RETURNINFO></RETURNINFOS></CONTENT>
4、测试代码及测试结果
XmlTools xmlTools = new XmlTools();
JSONObject jsonObject = null;
try {
jsonObject = xmlTools.documentToJSONObject(这里放xml);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/153a38f38a509fa086f164c2498b4567.png)