遇到解析xml的问题,从网上扒了各种工具,总结一下几个好用的。希望对大家也有用!
需要解析的xml:
String xmlString ="<?xml version=\"1.0\" encoding=\"utf-8\"?><msg v=\"1.0\" id=\"1536129180023\"><ctrl><userId>800218</userId><time>1536129190023</time><timestamp>1536129180023</timestamp><key>45ad652d1d21e2907be9e2fa3f70c112</key></ctrl><body><loto orderno=\"880324324566733\"/></body></msg>";
方法一返回Object:
/*循环解析XML将数据以json对象的形式返回*/
public static com.alibaba.fastjson.JSONObject xmlToJson(String xmlString){
Document doc = null;
com.alibaba.fastjson.JSONObject jsob=new com.alibaba.fastjson.JSONObject();
try{
doc = DocumentHelper.parseText(xmlString);
Element empRoot =doc.getRootElement();
if(empRoot.attributeCount()>0){
for(int i=0;i<empRoot.attributeCount();i++){
jsob.put(empRoot.attribute(i).getName(),empRoot.attribute(i).getStringValue());
}
}
for(Iterator root=empRoot.elementIterator();root.hasNext();){
Element emp1 = (Element)root.next();
jsob.put(emp1.getName(), emp1.getText());
for(Iterator emp1s=emp1.elementIterator();emp1s.hasNext();){
Element employee = (Element) emp1s.next();
jsob.put(employee.getName(), employee.getText());
List attrList1 = employee.attributes();
/*遍历节点内容*/
for (int i = 0; i < attrList1.size(); i++) {
Attribute item = (Attribute)attrList1.get(i);
jsob.put(item.getName(), item.getValue());
}
for(Iterator employees=employee.elementIterator();employees.hasNext();){
/*遍历节点内容*/
Element employeenew = (Element) employees.next();
/*节点名称和节点内容以KEY VALUE的方式保存到JSON对象*/
jsob.put(employeenew.getName(), employeenew.getText());
List attrList = employeenew.attributes();
for (int i = 0; i < attrList.size(); i++) {
Attribute item = (Attribute)attrList.get(i);
jsob.put(item.getName(), item.getValue());
}
}
}
}
}
catch(DocumentException e)
{
e.printStackTrace();
}
return jsob;
}
方法二返回Map:
/**
* xml转map 带属性
* @param xmlStr xmlStr
* @param needRootKey 是否需要在返回的map里加根节点键
* @return map
*/
public static Map<String, Object> xmlToMap(String xmlString, boolean needRootKey) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xmlString);
} catch (DocumentException e) {
e.printStackTrace();
}
Element root = doc.getRootElement();
Map<String, Object> map = xml2mapWithAttr(root);
if(root.elements().size()==0 && root.attributes().size()==0){
// 根节点只有一个文本内容
return map;
}
if(needRootKey){
// 在返回的map里加根节点键(如果需要)
Map<String, Object> rootMap = new HashMap<String, Object>();
rootMap.put(root.getName(), map);
return rootMap;
}
return map;
}
第一种输出:
{
"body": "",
"ctrl": "",
"id": "1536129180023",
"key": "45ad652d1d21e2907be9e2fa3f70c112",
"loto": "",
"orderno": "880324324566733",
"time": "1536129190023",
"timestamp": "1536129180023",
"userId": "800218",
"v": "1.0"
}
第二种输出:
{msg={@v=1.0, @id=1536129180023, ctrl={userId=800218, time=1536129190023, timestamp=1536129180023, key=45ad652d1d21e2907be9e2fa3f70c112}, body={loto={@orderno=880324324566733, #text=}}}}