dom4j创建和解析Xml例子

package createandparse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
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 Emoven
*
*/
public class XmlApp {
/**
* 创建xml
* @param fileName
*/
public static void createXml(String fileName){
Document document = DocumentHelper.createDocument();
Element employees = document.addElement("employees");
Element employee = employees.addElement("employee");
employee.addAttribute("id", "1"); //节点属性
Element name = employee.addElement("name");
name.setText("tom"); //节点内容
Element sex = employee.addElement("sex");
sex.setText("男");
Element age = employee.addElement("age");
age.setText("20");
try {
Writer fw = new FileWriter(fileName);
//XMLWriter xw = new XMLWriter(fw); //英文的可以这样创建
XMLWriter xw = new XMLWriter(new FileOutputStream(new File(fileName))); //解决中文乱码
xw.write(document);
xw.close();
System.out.println("创建xml成功!");
} catch (IOException e) {
e.printStackTrace();
}

}
/**
* 解析xml
* @param args
*/
public static void parseXml(String fileName){
File inputFile = new File(fileName);
SAXReader reader = new SAXReader();
try {
Document document = reader.read(inputFile);
Element employees = document.getRootElement();
for (Iterator i = employees.elementIterator();i.hasNext();) {
Element employee = (Element)i.next();
for (Iterator j = employee.elementIterator();j.hasNext();) {
Element node = (Element)j.next();
System.out.print(node.getName()+":"+node.getText()+"\t");
}
}
} catch (DocumentException e) {
e.printStackTrace();
}

}
public static void main(String[] args) {
createXml("d:\\createXml.xml");
//parseXml("d:\\createXml.xml");
}
}

注意:记得要导入dom4j-1.6.1.jar包

你可能感兴趣的:(dom4j)