package com.test; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import org.dom4j.Attribute; 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 Dom4jXMLRead { /*----------------------------------------------------------------------*/ /*----------------------------解析XML------------------------------------*/ /*----------------------------------------------------------------------*/ /** * 解析xml * @param url 文件地址aa * @return * @throws DocumentException */ public Document parse(String url) throws DocumentException{ SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; } /** * xml解析 元素处理 * @param document 解析后的dom对象 * @return */ @SuppressWarnings("unchecked") public void bar(Document document){ Element root = document.getRootElement(); //遍历root下的元素 for ( Iterator i = root.elementIterator(); i.hasNext(); ) { Element element = (Element) i.next(); // do something } // 遍历root下子节点是“foo”的节点元素 for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) { Element foo = (Element) i.next(); // do something } // 遍历根的属性 for ( Iterator i = root.attributeIterator(); i.hasNext(); ) { Attribute attribute = (Attribute) i.next(); // do something } } /*----------------------------------------------------------------------*/ /*-----------------------写XML------------------------------------------*/ /*----------------------------------------------------------------------*/ /** * 创建dom对象 */ public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Bob" ) .addAttribute( "location", "US" ) .addText( "Bob McWhirter" ); //…………………………可依次加自己的子节点 return document; } /** * 将dom写入硬盘 * @param document * @throws IOException */ public void write(Document document) throws IOException { XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) ); writer.write( document ); writer.close(); } /** * 测试运行 * @param args */ public static void main(String[] args) { Dom4jXMLRead readWrite = new Dom4jXMLRead(); Document document = readWrite.createDocument(); try { readWrite.write( document ); } catch (IOException e) { e.printStackTrace(); } } }