import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class ParseXmlString { public void parseXmlString(String str) { Document doc = null; try { // 读取并解析XML文档 // SAXReader就是一个管道,用一个流的方式,把xml文件读出来 // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档 // Document document = reader.read(new File("User.hbm.xml")); // 下面的是通过解析xml字符串的 doc = DocumentHelper.parseText(str); // 将字符串转为XML Element rootElt = doc.getRootElement(); // 获取根节点 System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称 Element codeElement=rootElt.element("CODE"); if("1".equals(codeElement.getTextTrim())){ //成功 Element headElement=rootElt.element("Head"); System.out.println("字段名:"+headElement.getTextTrim()); Element dataListElement=rootElt.element("DataList"); Iterator iter = dataListElement.elementIterator("Data"); Element dataElement=null; while (iter.hasNext()) { dataElement = (Element) iter.next(); System.out.println("字段值:"+dataElement.getTextTrim()); } }else{ //失败 Element descriElement=rootElt.element("DESCRIPTION"); System.out.println("异常说明:"+descriElement.getTextTrim()); } } catch (DocumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }