以下案例是日常开发中用到的dom4j工具类,该工具类有完成的解析数据过程,有完成的xml数据格式,支持单个参数,多个参数解析
代码如下:
public class Dom4jUtils {
/**
* 解析xml
* 备注:
* 要jar包:dom4j,fastjson
* 解析后的json格式不包含头部只包含里面内容,格式如下:
* {
* "APP_HEAD":{},
* "SYS_HEAD":{},
* "BODY":{}
* }
*
* @param xmlStr xml字符串
* @return
* @throws DocumentException
*/
public static JSONObject xmlToJson(String xmlStr) throws DocumentException {
Document doc = DocumentHelper.parseText(xmlStr);
JSONObject json = new JSONObject();
dom4jToJson(doc.getRootElement(), json);
return json;
}
/**
* 解析xml
*
* @param fileName 文件名称 相对路径
* @return
* @throws IOException
* @throws DocumentException
*/
public static JSONObject xmlToJsonByFile(String fileName) throws IOException, DocumentException {
//读取本地xml文件
String path = Thread.currentThread().getContextClassLoader().getResource(fileName).getPath();
//System.out.println(path);
//若文件名是中文则需要解码
//String filePath = URLDecoder.decode(path, "UTF-8");
//System.out.println(filePath);
//获取xml文件,并且转为utf-8格式
InputStreamReader isr = new InputStreamReader(new FileInputStream(path), "utf-8");
//把xml文件转换为String类型格式
String xmlStr = IOUtils.toString(isr);
Document doc = DocumentHelper.parseText(xmlStr);
JSONObject json = new JSONObject();
dom4jToJson(doc.getRootElement(), json);
return json;
}
/**
* xml转json
*
* @param element
* @param json
*/
public static void dom4jToJson(Element element, JSONObject json) {
//如果是属性
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isDElementEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
List<Element> chdEl = element.elements();
if (chdEl.isEmpty() && !isDElementEmpty(element.getText())) {//如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
}
for (Element e : chdEl) {//有子元素
if (!e.elements().isEmpty()) {//子元素也有子元素
JSONObject chdjson = new JSONObject();
dom4jToJson(e, chdjson);//递归调用
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray
JSONObject jsono = (JSONObject) o;
json.remove(e.getName());
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.put(e.getName(), chdjson);
}
}
} else {//子元素没有子元素
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isDElementEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
}
}
}
}
public static boolean isDElementEmpty(String str) {
if (str == null || str.trim().isEmpty() || "null".equals(str)) {
return true;
}
return false;
}
//测试
public static void main(String[] args) throws DocumentException, IOException {
//测试解析xml字符串
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<SERVICE>\n" +
" <SYS_HEAD>\n" +
" <USER_ID>000300</USER_ID>\n" +
" <TRAN_TIMESTAMP>161908</TRAN_TIMESTAMP>\n" +
" <BRANCH_ID>999999999</BRANCH_ID>\n" +
" <CORP_CODE>9999</CORP_CODE>\n" +
" <TRAN_DATE>20220526</TRAN_DATE>\n" +
" <ORG_SYS_ID>407020</ORG_SYS_ID>\n" +
" <SOURCE_TYPE>M46</SOURCE_TYPE>\n" +
" <ESB_SEQ_NO>50010120220526010000125387</ESB_SEQ_NO>\n" +
" <PROVIDER_ID>408030</PROVIDER_ID>\n" +
" <CONSUMER_SEQ_NO>40702020220526020027075438</CONSUMER_SEQ_NO>\n" +
" <SERVICE_SCENE>25</SERVICE_SCENE>\n" +
" <CONSUMER_ID>407020</CONSUMER_ID>\n" +
" <SERVICE_CODE>11002000107</SERVICE_CODE>\n" +
" </SYS_HEAD>\n" +
" <APP_HEAD>\n" +
" <BUSS_SEQ_NO>40702020220526020027075438</BUSS_SEQ_NO>\n" +
" </APP_HEAD>\n" +
" <LOCAL_HEAD></LOCAL_HEAD>\n" +
" <BODY>\n" +
" <OPERATION_TYPE>0</OPERATION_TYPE>\n" +
" <APPLYER_USER_ID>000300</APPLYER_USER_ID>\n" +
" <RSK_INFO_ARRAY>\n" +
" <CLNT_ACCT_NO>6214808801001776505</CLNT_ACCT_NO>\n" +
" <CUST_ACCT_NO_TP>1</CUST_ACCT_NO_TP>\n" +
" <OPEN_BRANCH>330100100</OPEN_BRANCH>\n" +
" <REASON_MSG>测试数据1</REASON_MSG>\n" +
" </RSK_INFO_ARRAY>\n" +
" <RSK_INFO_ARRAY>\n" +
" <CLNT_ACCT_NO>3301020109800083693</CLNT_ACCT_NO>\n" +
" <CUST_ACCT_NO_TP>1</CUST_ACCT_NO_TP>\n" +
" <OPEN_BRANCH>330100100</OPEN_BRANCH>\n" +
" <REASON_MSG>测试数据2</REASON_MSG>\n" +
" </RSK_INFO_ARRAY>\n" +
" <RSK_INFO_ARRAY>\n" +
" <CLNT_ACCT_NO>6214808801021786849</CLNT_ACCT_NO>\n" +
" <CUST_ACCT_NO_TP>1</CUST_ACCT_NO_TP>\n" +
" <OPEN_BRANCH>330100100</OPEN_BRANCH>\n" +
" <REASON_MSG>测试数据3</REASON_MSG>\n" +
" </RSK_INFO_ARRAY>\n" +
" <ORG_INFO_ARRAY>\n" +
" <ORG_NO>991000055</ORG_NO>\n" +
" <ORG_NAME>上海工商机构</ORG_NAME>\n" +
" </ORG_INFO_ARRAY>\n" +
" </BODY>\n" +
"</SERVICE>";
JSONObject jsonObject = xmlToJson(xmlStr);
System.out.println(jsonObject);
//java 解析json数据
JSONObject body = jsonObject.getJSONObject("BODY");
System.out.println(body);
String operation_type = body.getString("OPERATION_TYPE");
String applyer_user_id = body.getString("APPLYER_USER_ID");
System.out.println("operation_type:" + operation_type);
System.out.println("applyer_user_id:" + applyer_user_id);
//解析数组
Object rsk_infoObject = body.get("RSK_INFO_ARRAY");
JSONArray rsk_info_array = null;
if (rsk_infoObject != null) {
//判断object是对象还是数组
if (rsk_infoObject instanceof JSONObject) {
JSONObject jsonObj = (JSONObject) rsk_infoObject;
rsk_info_array = new JSONArray();
rsk_info_array.add(jsonObj);
} else if (rsk_infoObject instanceof JSONArray) {
rsk_info_array = (JSONArray) rsk_infoObject;
}
}
for (int i = 0; i < rsk_info_array.size(); i++) {
JSONObject obj = rsk_info_array.getJSONObject(i);
String cust_acct_no_tp = obj.getString("CUST_ACCT_NO_TP");
String open_branch = obj.getString("OPEN_BRANCH");
String clnt_acct_no = obj.getString("CLNT_ACCT_NO");
String reason_msg = obj.getString("REASON_MSG");
System.out.println("cust_acct_no_tp:" + cust_acct_no_tp);
System.out.println("open_branch:" + open_branch);
System.out.println("clnt_acct_no:" + clnt_acct_no);
System.out.println("reason_msg:" + reason_msg);
}
//获取ORG_INFO_ARRAY数据(当一条数据时是jsonobject,当大于一条数据时是jsonarray)
Object orgInfoObject = body.get("ORG_INFO_ARRAY");
JSONArray org_info_array = null;
if (orgInfoObject != null) {
//判断object是对象还是数组
if (orgInfoObject instanceof JSONObject) {
JSONObject jsonObj = (JSONObject) orgInfoObject;
org_info_array = new JSONArray();
org_info_array.add(jsonObj);
} else if (orgInfoObject instanceof JSONArray) {
org_info_array = (JSONArray) orgInfoObject;
}
}
for (int i = 0; i < org_info_array.size(); i++) {
JSONObject obj = org_info_array.getJSONObject(i);
String org_no = obj.getString("ORG_NO");//机构号
String org_name = obj.getString("ORG_NAME");//机构名称
System.out.println("org_no:" + org_no);
System.out.println("org_name:" + org_name);
}
//测试读取本地xml文件
String fileName = "xml/company_info.xml";
JSONObject object = xmlToJsonByFile(fileName);
System.out.println(object);
}
}
备注:读取xml数据有两种方式,一种是读取xml字符串格式,一种是读取配置文件格式
读取配置文件格式如下:
以上工具类,main方法可以正常运行,可以自行执行看看效果,这里就不再贴出执行效果,本人总结的文档,基本基于工作案例,能够正常运行的代码,分享技术,是我的快乐。