dom4j 解析 xml 非常好用

package com.xml.test;

import java.io.ByteArrayInputStream;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class TestXml {
public static void ReadXml(String xmlstring){
ByteArrayInputStream inst=null;
System.out.println("-----------------------"+xmlstring);
xmlstring=xmlstring.replaceAll("null","");

System.out.println("-----------------------"+xmlstring);
try
{

String method="";
SAXReader reader = new SAXReader();
inst=new ByteArrayInputStream(xmlstring.getBytes());
Document xmltable = reader.read(inst);
Element tableroot=xmltable.getRootElement();
if("user".equals(tableroot.getName())){
String userid=xmltable.selectSingleNode("//user/userid").getText();
String password=xmltable.selectSingleNode("//user/password").getText();
String sex=xmltable.selectSingleNode("//user/sex").getText();
String name=xmltable.selectSingleNode("//user/name").getText();
/*String birthday=xmltable.selectSingleNode("//doc/doc-record/birthday").getText();
String mail=xmltable.selectSingleNode("//doc/doc-record/mail").getText();
String address=xmltable.selectSingleNode("//doc/doc-record/address").getText();
*/
System.out.println("---------------------userid:"+userid);
System.out.println("---------------------password:"+password);
System.out.println("---------------------sex:"+sex);
System.out.println("---------------------name:"+name);
System.out.println("---------------------");
System.out.println("---------------------");
System.out.println("---------------------");

method=xmltable.selectSingleNode("//doc/doc-record/method").getText();
System.out.println("---------------------method:"+method);
}
}catch(Exception e){
System.out.println("-------------------------::::"+e.getMessage());
}

}

public static void main(String args[]){
String str="";

StringBuffer strxml=new StringBuffer();
strxml.append("<?xml version=/"1.0/" encoding=/"gb2312/"?>");
strxml.append("<user>");
strxml.append("<userid>");
strxml.append("zhanghouying");
strxml.append("</userid>");
strxml.append("<password>");
strxml.append("111111");
strxml.append("</password>");

strxml.append("<sex>");
strxml.append("1");
strxml.append("</sex>");

strxml.append("<name>");
strxml.append("张厚营");
strxml.append("</name>");


strxml.append("</user>");

System.out.println("-----------------------"+strxml);
TestXml.ReadXml(strxml.toString());
}
}

你可能感兴趣的:(dom4j)