class="java" name="code"> import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import javax.management.modelmbean.XMLParseException; 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; import com.ailk.xmlparserdemon.intf.XmlDocument; public class Dom4jXmlDemon implements XmlDocument { static String fileName; public void createDocument(String fileName) { System.out.println("DOM4j create begin..."); try { Document dt= DocumentHelper.createDocument(); Element employees= dt.addElement("employees"); Element employee=employees.addElement("employee"); Element name=employee.addElement("name"); name.setText("小明"); Element sex=employee.addElement("sex"); sex.setText("m"); Element parents=employee.addElement("parents"); Element father=parents.addElement("father"); father.setText("小张"); Element mother=parents.addElement("mother"); mother.setText("小慧"); FileWriter fw=new FileWriter(fileName); XMLWriter xw=new XMLWriter(fw); xw.write(dt); xw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("DOM4j create complete..."+fileName); } public void parserDocument(String fileName) { System.out.println("DOM4j parser begin..."); try { File file=new File(fileName); SAXReader saxReader=new SAXReader(); Document dt=saxReader.read(file); Element employees=dt.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(); for(Iterator k=node.elementIterator();k.hasNext();){ Element lastNode=(Element) k.next(); System.out.println(lastNode.getName()+":"+lastNode.getText()); } if(!node.elementIterator().hasNext()){ System.out.println(node.getName()+":"+node.getText()); } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("DOM4j parser complete..."); } public static void main(String[] args){ Dom4jXmlDemon dom4j=new Dom4jXmlDemon(); Dom4jXmlDemon.fileName="E:\\OneNote\\dom4j.xml"; dom4j.createDocument(fileName); dom4j.parserDocument(fileName); } }