package com.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class dom4j {
public static void DOM4JCreateXML(){
org.dom4j.Document document = DocumentHelper.createDocument();
org.dom4j.Element bookstore = document.addElement("bookstore");
org.dom4j.Element book = bookstore.addElement("book");
book.addAttribute("id", "1");
org.dom4j.Element name = book.addElement("name");
name.setText("小王子");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
File file = new File("books4.xml");
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(file), format);
writer.setEscapeText(false);
writer.write(document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void DOM4JreadXML() throws DocumentException{
SAXReader sr=new SAXReader();
Document Document = sr.read(new File("pom1.xml"));
Element root=Document.getRootElement();
Iterator it=root.elementIterator();
while(it.hasNext()) {
Element ele=(Element) it.next();
List<Attribute> list=ele.attributes();
for(Attribute attr:list) {
System.out.println(attr.getName()+":"+attr.getValue());
}
Iterator suneles=ele.elementIterator();
while(suneles.hasNext()) {
Element ele1=(Element) suneles.next();
System.out.println(ele1.getName()+":"+ele1.getStringValue());
}
}
}
public static void main(String[] args) throws DocumentException {
// DOM4JreadXML();
DOM4JCreateXML();
}
}