在日常工作中,可能会遇到需要将xml格式转化为json格式的情况,下面为我自己写的小例子。希望可以给大家一些帮助。
一、代码部分
package com.neusoft.jiangsupatch.bo;
import java.io.File;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* XML转JSONObject实现
* @author
*
*/
public class TestXmlToJson {
/**
* 将element转成JSONObject
* 属性与子节点为最小单元不再进行递归
* @param node
* @return
*/
@SuppressWarnings("unchecked")
public static JSONObject elementToJSONObject(Element node) {
JSONObject result = new JSONObject();
// 当前节点的名称、文本内容和属性(属性变为子标签)
List listAttr = node.attributes();// 当前节点的所有属性的list
for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
result.put(attr.getName(), attr.getValue());
}
// 递归遍历当前节点所有的子节点
List 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 {
// 若存在子节点或者属性不为空,要继续向下一级转化;当下一级存在相同标签时,转为数组;下一级不存在相同标签,仍为json对象
if (!hasCF(e.elements())) {
result.put(e.getName(), elementToJSONObject(e));
} else {
result.put(e.getName(), elementToJSONArray(e));
}
}
}
}
return result;
}
/**
* 将element转成JSONArray
*
* @param node
* @return
*/
@SuppressWarnings("unchecked")
public static JSONArray elementToJSONArray(Element node) {
JSONArray result = new JSONArray();
List listElement = node.elements();// 所有一级子节点的list
if (!listElement.isEmpty()) {
for (Element e : listElement) {// 遍历所有一级子节点
JSONObject json = new JSONObject();
json.put(e.getName(), elementToJSONObject(e));
result.add(json);
}
}
return result;
}
/**
* 读取文本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;
}
}
/**
* 判断list中是否存在相同的element
* @param elements
* @return
*/
public static boolean hasCF(List elements) {
Boolean flag = false;
for (int i = 0; i < elements.size() - 1; i++) {
if (elements.get(i).getName().equals(elements.get(i + 1).getName())) {
flag = true;
}
}
return flag;
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args) {
String json = "";
try {
json = elementToJSONObject(
getDocumentByReadText(
"C:\\Users\\Administrator\\Desktop\\1.xml")
.getRootElement()).toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("转换json失败");
}
System.out.println(json);
}
}
二、原xml格式如下:
32040001013202002018110510518
1
3202990101
3204000101
TAX
20181105
20181105171132
CBXX005
320200
0
0
1000000000030419
228083803
120100
10176248
1
41
1
2
201801
201812
N
1
20181031163227
1
11
20181031153205
1000000000030421
228083813
120100
10176248
1
41
1
2
201801
201812
N
1
20181031163227
1
11
20181031153205
三、生成对应的json字符串如下:
{
"grphdr": {
"appseriono": "32040001013202002018110510518",
"cfbz": "1",
"aaz400": "3202990101",
"sendcode": "3204000101",
"receivecode": "TAX",
"senddate": "20181105",
"sendtime": "20181105171132",
"typecode": "CBXX005",
"typename": "",
"ptszqh": "320200",
"sign": "",
"dgst": "",
"bodyisfile": "0",
"filename": "",
"filepath": "",
"appmentno": "",
"appcount": "0",
"appcode": "",
"exceptionmessage": ""
},
"busitext": {
"record": [
{
"jcxx": {
"xh": "1000000000030419",
"aaz400": "228083803",
"sbuuid": "120100",
"aab001": "10176248",
"aaa027": "1",
"aae140": "41",
"aaa067": "1",
"aaa042": "2",
"aae041": "201801",
"aae042": "201812",
"hxbz": "N",
"aab099": "1",
"aae036": "20181031163227",
"aaa321": "1",
"aaa322": "11",
"aae418": "20181031153205"
}
},
{
"jcxx": {
"xh": "1000000000030421",
"aaz400": "228083813",
"sbuuid": "120100",
"aab001": "10176248",
"aaa027": "1",
"aae140": "41",
"aaa067": "1",
"aaa042": "2",
"aae041": "201801",
"aae042": "201812",
"hxbz": "N",
"aab099": "1",
"aae036": "20181031163227",
"aaa321": "1",
"aaa322": "11",
"aae418": "20181031153205"
}
}
]
}
}
喜欢我的文章希望和我一起成长的宝宝们,可以搜索并添加公众号TryTestwonderful ,或者扫描下方二维码添加公众号