dom4j生成和解析xml文件
package com.test;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* @说明 DOM4J解析XML
* @author cuisuqiang
* @version 1.0
* @since
*/
@SuppressWarnings("unchecked")
public class Dom4jDemo {
public static void main(String[] args) {
String file = "C:\\p.xml"; // 文件存放位置
Dom4jDemo dj = new Dom4jDemo();
dj.createXml(file);
dj.parserXml(file);
}
/**
* 生成XML
* @param filePath 文件路径
*/
public void createXml(String filePath) {
Document document = DocumentHelper.createDocument();
Element employees = document.addElement("persons");
Element employee = employees.addElement("person");
Element name = employee.addElement("name");
name.setText("java小强");
Element sex = employee.addElement("sex");
sex.setText("男");
Element age = employee.addElement("age");
age.setText("26");
try {
// PrintWriter带有编码格式的构造方法有助于解决乱码问题
PrintWriter pw = new PrintWriter(filePath, "utf-8");
XMLWriter xmlWriter = new XMLWriter(pw);
xmlWriter.write(document);
xmlWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析XML
* @param filePath 文件路径
*/
public void parserXml(String filePath) {
File inputXml = new File(filePath);
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputXml);
Element root = document.getRootElement();
for (Iterator persons = root.elementIterator(); persons.hasNext();) {
Element person = (Element) persons.next();
for (Iterator pro = person.elementIterator(); pro.hasNext();) {
Element node = (Element) pro.next();
System.out.print(node.getName() + ":" + node.getText() + "\t");
}
System.out.println();
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}