使用dom4j解析XML字符串
package sides;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @description 解析xml字符串
*/
public class XmlStringTest {
/**
* @description 获取将xml字符串节点
* @param xml
*/
@SuppressWarnings("unchecked")
public static void readStringXmlOut(String xml) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
Element rootElt = doc.getRootElement(); // 获取根节点
System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
String total = rootElt.elementText("total");
System.out.println("total:"+total);
Iterator iter = rootElt.elementIterator("docs"); // 获取根节点下的子节点head
// 遍历head节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
String docstring = recordEle.elementTextTrim("doc"); // 拿到XXX节点下的子节点XXX值
System.out.println("doc:" + docstring);
Iterator iters = recordEle.elementIterator("doc"); // 获取子节点XXX下的子节点XXX
// 遍历XXX节点下的XXX节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
String bizid = itemEle.elementTextTrim("bizid"); // 拿到XXX下的子节点XXX下的字节点XXX的值
String name = itemEle.elementTextTrim("name");
System.out.println("bizid:" + bizid);
System.out.println("name:" + name);
}
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// 下面是需要解析的xml字符串例子
String xmlString = "<?xml version="1.0" encoding="utf-8" ?><search> <total>总记录数(检索中所有匹配的记录数量)</total>"
+"<result_num>当前页中返回的结果数量</result_num><spend_time>检索耗费时间</spend_time>"
+"<city >UTF-8编码的请求城市字符串</city ><addr >UTF-8 编码的请求地址字符串</addr >"
+"<key >UTF-8编码的请求keyword 字符串</key ><docs><doc>"
+"<bizid>加密后的商户bid</bizid><name>UTF-8编码的商户名称</name>"
+"<tel>UTF-8 编码的商户电话</tel><addr>UTF-8编码的商户地址</addr>"
+"<desc>UTF-8编码的商户简介</desc><dist>距离中心点的距离(-1 表示无距离,单位为公里)</dist>"
+"<mapxy>加密的坐标,xy 用”,”分隔</mapxy><detail>进入商户详情的 url</detail>"
+"</doc><doc>"
+"<bizid>加密后的商户bid</bizid><name>UTF-8编码的商户名称</name>"
+"<tel>UTF-8 编码的商户电话</tel><addr>UTF-8编码的商户地址</addr>"
+"<desc>UTF-8编码的商户简介</desc><dist>距离中心点的距离(-1 表示无距离,单位为公里)</dist>"
+"<mapxy>加密的坐标,xy 用”,”分隔</mapxy><detail>进入商户详情的 url</detail>"
+"</doc></docs></search> ";
readStringXmlOut(xmlString);
}
}