package study;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class demoxml {
public static void main(String[] args) {
Document doc=DocumentHelper.createDocument();
Element addresslist=doc.addElement("addresslist");
Element linkman=addresslist.addElement("linkman");
Element name=linkman.addElement("name");
Element email=linkman.addElement("email");
name.setText("土豆");
email.setText("123456@qq.com");
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
try {
XMLWriter writer = new XMLWriter(new FileOutputStream(new File("E:" + File.separator + "dom4j.xml")), format);
writer.write(doc);
writer.close();
}catch (IOException ee){
ee.printStackTrace();
}
}
}
package study;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.*;
import java.io.File;
import java.util.Iterator;
public class demoxml {
public static void main(String[] args) {
File file=new File("E:"+File.separator+"dom4j.xml");
SAXReader reader=new SAXReader();
Document doc=null;
try{
doc=reader.read(file);
}catch (DocumentException e){
e.getMessage();
}
Element root=doc.getRootElement();
Iterator iter=root.elementIterator();
while (iter.hasNext()){
Element linkman=(Element) iter.next();
System.out.println("姓名:"+linkman.elementText("name"));
System.out.println("邮件"+linkman.elementText("email"));
}
}
}