感谢博主:
https://blog.csdn.net/tkggetg/article/details/47784321
依赖:
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!--FASTJSON是当今处理json效率最高的json处理工具-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
代码:
public JSONObject downapk() {
JSONObject json=new JSONObject();
try {
File file=new File("/root/server/down_apk.xml");
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
//fc向buffer中读入数据
fc.read(bb);
bb.flip();
String xml=new String(bb.array(),"UTF8");
Document doc= DocumentHelper.parseText(xml);
dom4j2Json(doc.getRootElement(), json);
fc.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
greet = HandlerComm.greet_10003;
}
json.put("message", greet);
json.put(HandlerComm.msgNote, HandlerComm.getErrorMsg(greet));
return json;
}
public static void dom4j2Json(Element element,JSONObject json){
//如果是属性
for(Object o:element.attributes()){
Attribute attr=(Attribute)o;
if(!isEmpty(attr.getValue())){
json.put("@"+attr.getName(), attr.getValue());
}
}
List<Element> chdEl=element.elements();
if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
json.put(element.getName(), element.getText());
}
for(Element e:chdEl){//有子元素
if(!e.elements().isEmpty()){//子元素也有子元素
JSONObject chdjson=new JSONObject();
dom4j2Json(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(!isEmpty(attr.getValue())){
json.put("@"+attr.getName(), attr.getValue());
}
}
if(!e.getText().isEmpty()){
json.put(e.getName(), e.getText());
}
}
}
}
public static boolean isEmpty(String str) {
if (str == null || str.trim().isEmpty() || "null".equals(str)) {
return true;
}
return false;
}