首先要导入dom4j的jar包
代码:
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class dom4jDemo {
public static void main(String[] args) {
String xml =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://www.seecom.com.cn/webservice\">" +
" <soapenv:Header/>" + " <soapenv:Body>" +
" <web:getChargeRequest>" + " <web:charge>" +
" <web:channel>205</web:channel>" +
" <web:pwd>fea1920da4045adeafda10bcd47f3c9f</web:pwd>" +
" <web:orderNo>446666</web:orderNo>" +
" <web:phone>13280009999</web:phone>" +
" <web:money>12</web:money>" + " </web:charge>" +
" </web:getChargeRequest>" + " </soapenv:Body>" +
"</soapenv:Envelope>";
Map<String, String> map = readXmlToMap(xml);
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
}
/**
* @功能描述: 解析提交结果
*
* @param xml
* @return
*
* @作者:zhangpj @创建时间:2018年4月14日
*/
public static Map<String, String> readXmlToMap(String xml) {
Document doc = null;
Map<String, String> resultMap = new HashMap<String, String>();
try {
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
Element bodyElement = rootElt.element("Body");
Element getChargeResponseElement = bodyElement.element(
"getChargeRequest");
Element chargeElement = getChargeResponseElement.element("charge");
try {
// 方式一,直接获取
// String channel=chargeElement.elementTextTrim("channel");
// String pwd=chargeElement.elementTextTrim("pwd");
// String orderNo=chargeElement.elementTextTrim("orderNo");
// String phone=chargeElement.elementTextTrim("phone");
// String money=chargeElement.elementTextTrim("money");
//
// resultMap.put("channel", channel);
// resultMap.put("pwd", pwd);
// resultMap.put("orderNo", orderNo);
// resultMap.put("phone", phone);
// resultMap.put("money", money);
// 方式二,迭代器获取
Iterator<Element> it = chargeElement.elementIterator();
// 遍历
while (it.hasNext()) {
// 获取某个子节点对象
Element e = it.next();
// 对子节点进行遍历
resultMap.put(e.getName(), e.getStringValue().trim());
}
} catch (Exception e) {
e.printStackTrace();
//发生异常以后设置为处理中
resultMap.put("status", "underway");
}
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
}
转载于:https://blog.51cto.com/1197822/2157739