package com.example.xmlresovler;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Demo4jXmlResovlerDao {
/**
* demo4j解析xml
*/
public static Map xmlResovlerDao(String xml) {
Map map=new HashMap();
SAXReader saxReader=new SAXReader();
Document doc=null;
try {
//字符串转xml
doc=DocumentHelper.parseText(xml);
//获取根节点
Element rootElt = doc.getRootElement(); // 获取根节点
//打印根节点名字
System.out.println("根节点名字:"+rootElt.getName());
//获取根节点下的所有子节点
//<?xml version="1.0" encoding="UTF-8"?>
//
//922609
//会员创建成功
//
String returnCode=rootElt.elementTextTrim("returnCode");
String message=rootElt.elementTextTrim("message");
map.put("returnCode", returnCode);
map.put("message", message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 将字符串转为XML
return map;
}
}
2.JDOM解析xml字符串
需要导入jar包jdom-1.1.3.jar
package com.example.xmlresovler;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
/**
* JDOM解析
* @author admin
*
*/
public class JDOMXmlResovlerDao {
public static Map xmlResovlerDao(String xml) throws Exception {
Map map=new HashMap();
SAXBuilder saxBuilder = new SAXBuilder();
//创建一个输入流,加载xml文件
//InputStream in = new FileInputStream("src/mm.xml");
//解析xml字符串
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource in = new InputSource(read);
Document document = saxBuilder.build(in);
//获取根节点
Element rootElement = document.getRootElement();
List elements = rootElement.getChildren();
//获取属性值
for (Element element : elements) {
map.put(element.getName(), element.getValue());
}
return map;
}
}