pom.xml
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONObject;
/**
* 解析类
*/
public class XMLDone {
//解析xml并封装成json对象返回
public synchronized JSONObject XML(String xmlDoc) throws UnsupportedEncodingException, DocumentException{
String a = "<?xml version='1.0' encoding='UTF-8'?><Request service='RoutePushService' lang='zh-CN'><Body><WaybillRoute id='448310' mailno='444008484833' orderid='AC8110930011' acceptTime='2018-11-19 12:47:24' acceptAddress='江苏省常州市XXXX' remark='备注' opCode='80'/></Body></Request>";
xmlDoc = "<Request service='RoutePushService' lang='zh-CN'><Body><WaybillRoute id='10049361064087' mailno='444000010085' orderid='A1811093001' acceptTime='2017-12-31 18:30:00' acceptAddress='江苏省常州市XXXX' remark='上门收件' opCode='50'/></Body></Request>";
JSONObject jsonObject = new JSONObject();
Document doc = null;
SAXReader xmlReader = new SAXReader();
doc = xmlReader.read(new ByteArrayInputStream(xmlDoc.getBytes("UTF-8")));
Element rootElt = doc.getRootElement(); // 获取根节点
String service = rootElt.attributeValue("service");
System.out.println(rootElt.getName()+"-->"+"service="+service);
//Body节点
Iterator iterBody = rootElt.elementIterator("Body");
System.out.println("iterBody=="+iterBody.hasNext());
while(iterBody.hasNext()){
Element recordBody = (Element) iterBody.next();
Iterator iterWaybillRoute = recordBody.elementIterator("WaybillRoute");
while(iterWaybillRoute.hasNext()){
Element recordWaybillRoute = (Element)iterWaybillRoute.next();
//id
Attribute id = recordWaybillRoute.attribute("id");
jsonObject.put("id", id.getValue());
//mailno
Attribute mailno = recordWaybillRoute.attribute("mailno");
jsonObject.put("mailno", mailno.getValue());
//orderid
Attribute orderid = recordWaybillRoute.attribute("orderid");
jsonObject.put("orderid", orderid.getValue());
//acceptTime
Attribute acceptTime = recordWaybillRoute.attribute("acceptTime");
jsonObject.put("acceptTime", acceptTime.getValue());
//acceptAddress
Attribute acceptAddress = recordWaybillRoute.attribute("acceptAddress");
jsonObject.put("acceptAddress", acceptAddress.getValue());
//remark
Attribute remark = recordWaybillRoute.attribute("remark");
jsonObject.put("remark", remark.getValue());
//opCode
Attribute opCode = recordWaybillRoute.attribute("opCode");
jsonObject.put("opCode", opCode.getValue());
}
}
return jsonObject;
}
}