//首先要下载dom4j.jar
//示例1
package dom4jdemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringBufferInputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Dom4jParseDemo {
public static void main(String[] args) {
String xml="";
xml+="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xml+="<root>";
xml+="<users userId=\"1\">";
xml+="<username>admin</username>";
xml+="<password>111</password>";
xml+="<quanxian>0</quanxian>";
xml+="<underling><name>under1</name></underling>";
xml+="</users>";
xml+="<users userId=\"2\">";
xml+="<username>hehe</username>";
xml+="<password>张三</password>";
xml+="<quanxian>1</quanxian>";
xml+="<underling><name>under1</name></underling>";
xml+="</users>";
xml+="<users userId=\"3\">";
xml+="<username>李鹏</username>";
xml+="<password>111</password>";
xml+="<quanxian>2</quanxian>";
xml+="<underling><name>under1</name></underling>";
xml+="</users>";
xml+="<users userId=\"4\">";
xml+="<username>java</username>";
xml+="<password>111</password>";
xml+="<quanxian>1</quanxian>";
xml+="<underling><name>under1</name></underling>";
xml+="</users>";
xml+="</root>";
SAXReader saxReader = new SAXReader();
try {
//File file=new File("C:\\test.xml");
//FileInputStream in=new FileInputStream(file);
//Document document = saxReader.read(in);//从文件流读入xml数据
StringBufferInputStream strInStream=new StringBufferInputStream(xml);
Document document = saxReader.read(strInStream);//从STRING对象读入XML数据
Element root = document.getRootElement();
List listUsers=root.selectNodes("users");
for(int i=0;i<listUsers.size();i++){
Element eleUser=(Element)listUsers.get(i);
Node nodeUsername=eleUser.selectSingleNode("username");
Node nodePassword=eleUser.selectSingleNode("password");
System.err.println("username:"+nodeUsername.getText());
System.err.println("password:"+nodeUsername.getText());
//System.err.println("username:"+nodeUsername.getStringValue());
//System.err.println("password:"+nodePassword.getStringValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//示例2
package dom4jdemo;
import java.io.File;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jUpdateDemo {
public int createXMLFile(String filename){
/** 返回操作结果, 0表失败, 1表成功 */
<