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;
public class Dom4jDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String filePath = "F:\\mystudty\\resourses\\create_parser_dom4j_xml.xml";
File file = new File(filePath);
createXML(file);
parserXML(file);
}
/**
* 生成xml文件
* @param file
*/
private static void createXML(File file){
Document document = DocumentHelper.createDocument();
Element companys = document.addElement("companys");
for(int i=0;i<10;i++){
Element company = companys.addElement("company");
Element name = company.addElement("name");
name.setText("Company_"+i);
Element webAddress = company.addElement("webAddress");
webAddress.setText("www.company_"+i+".com");
company.addAttribute("add", "address_"+i);
}
try {
PrintWriter pw = new PrintWriter(file,"utf-8");
XMLWriter xmlWriter = new XMLWriter(pw);
xmlWriter.write(document);
xmlWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析xml文件
* @param file
*/
private static void parserXML(File file){
SAXReader saxReader = new SAXReader();
Document document;
try {
document = saxReader.read(file);
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());
System.out.print("\t");
}
System.out.println();
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}