DOM4J读写xml工具 package com.dom4j;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.List;import org.dom4j.Document;import org.do
package com.dom4j; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; 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 ParseXml { SAXReader reader =new SAXReader(); public void readerxml() { Document document = null; try { document = reader.read("d:/kzw/1.xml"); } catch (DocumentException e) { System.out.println("读取xml文件失败!"); } Element rootElement = document.getRootElement(); List< Element> eles= rootElement.elements(); for (Element element : eles) { System.out.println(element.getName()+" = "+element.attributeValue("name")); } } public void createxml() { Document newxml = DocumentHelper.createDocument(); Element rootElement = newxml.addElement("data"); Element elementmusi = rootElement.addElement("music"); elementmusi.addAttribute("name","kao"); elementmusi.addAttribute("id", "1"); for (int i = 0; i <10; i++) { Element element = elementmusi.addElement("song"); element.addAttribute("id",i+""); element.addAttribute("name","泡沫"); element.addAttribute("size","5M"); element.addAttribute("filepath", "c:/kzw/mi.mp4"); } OutputFormat format = new OutputFormat(); format.setEncoding("UTF-8"); try { writexml(new FileOutputStream("d:/out.xml"),format,newxml); } catch (FileNotFoundException e) { System.out.println("输出文件流创建失败!"); } } public void writexml(FileOutputStream os,OutputFormat format,Document document) { XMLWriter writer= null; try { writer = new XMLWriter(os, format); } catch (UnsupportedEncodingException e) { System.out.println("创建xml写流出错!"); } try { writer.write(document); writer.flush(); } catch (IOException e) { System.out.println("写xml文件出错"); } try { writer.close(); } catch (IOException e) { System.out.println("写xml文件流关闭失败!"); } } }dom4j-1.6.1.jar dom4j-1.6.1.jar