DOM4J
package cn.xxx.test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class DOM4JWriter {//实现xml文件的输出 @SuppressWarnings("deprecation") public static void main(String[] args) throws IOException { int[] ids=new int[]{10,20,30}; String[] title=new String[]{"红楼梦","三国演义","水浒传"}; Double[] price=new Double[]{1.2,2.3,2.4}; //创建Document对象 Document document = DocumentHelper.createDocument(); Element booksElt=document.addElement("books");//设置根元素 for(int i=0;i<ids.length;i++){ Element bookElt = booksElt.addElement("book");//创建book节点 bookElt.addAttribute("id",String.valueOf(ids[i])); Element titleElt = bookElt.addElement("title");//创建title节点 Element priceElt = bookElt.addElement("price"); titleElt.setText(title[i]); priceElt.setText(String.valueOf(price[i])); } //输出格式类 //OutputFormat format=OutputFormat.createCompactFormat();//紧凑型 OutputFormat format=OutputFormat.createPrettyPrint();//缩进型 format.setEncoding("UTF-8"); //文档输出类 XMLWriter out=new XMLWriter(new FileOutputStream("d:"+File.separator+"book.xml"),format); out.write(document); } }
package cn.xxx.test; import java.io.File; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class DOM4JReader {//xml文件的读取 public static void main(String[] args) throws Exception{ File file=new File("d:"+File.separator+"book.xml"); SAXReader sax=new SAXReader();//创建一个SAX解析器对象 Document document=sax.read(file); Element booksElt = document.getRootElement();//获取根元素 books List elements = booksElt.elements(); Iterator it = elements.iterator(); while(it.hasNext()){ Element bookElt = (Element) it.next();//book节点 System.out.print("id="+bookElt.attributeValue("id")+",");//book的id属性 System.out.print("title="+bookElt.elementText("title")+",");//book的title节点 System.out.println("price="+bookElt.elementText("price")); } } }