dom4j简单读写xml文件
程序员文章站
2022-05-28 22:41:54
...
生成xml文件 XMLDom4jAtWrite .java
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class XMLDom4jAtWrite {
public static void main(String[] args) throws IOException {
Document doc = DocumentHelper.createDocument();
//节点
Element elements = doc.addElement("users");
Element username = elements.addElement("username");
Element pass = elements.addElement("password");
//属性
username.addAttribute("type","button");
username.setText("110");
pass.setText("password");
//生成-加上xml格式
XMLWriter xmlWriter = new XMLWriter(new FileWriter("c:/m.xml"),OutputFormat.createPrettyPrint());
xmlWriter.write(doc);
xmlWriter.close();
System.out.println("end-");
}
}
读取xml文件 XMLDom4jAtRead .java
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XMLDom4jAtRead {
public static void main(String[] args) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(new FileReader(new File("c:/mail.xml")));
} catch (Exception e) {
e.printStackTrace();
System.out.println("error 403");
}
Element listElement = document.getRootElement();
Iterator<Element> elem = listElement.elementIterator();
while (elem.hasNext()) {
Element e = elem.next();
Iterator<Element> elem2 = e.elementIterator();
while(elem2.hasNext()){
Element e2 = elem2.next();
System.out.print(e2.getName()+":"+e2.getText());
}
}
System.out.println("end-");
}
}
所需jar包:dom4j-2.0.0-RC1.jar
链接:http://pan.baidu.com/s/1mgR7uGS