首页 > 代码库 > Dom4j写XML

Dom4j写XML

package com;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 Text {  public static void main(String[] args) {    //创建文档并设置文档根节点元素:第1种方式//    Document document=DocumentHelper.createDocument();//    Element root=DocumentHelper.createElement("student");//    document.setRootElement(root);          //创建文档并设置文档根节点元素:第2种方式    Element root=DocumentHelper.createElement("student");     Document document=DocumentHelper.createDocument(root);    //在节点内添加属性    root.addAttribute("name", "majun");    //创建一个新的节点hello放在root下面    Element  helloelement1=root.addElement("hello");    //设置节点hello的内容为hello    helloelement1.setText("hello");    //设置输出的格式    OutputFormat  format=new  OutputFormat("   ",true);    XMLWriter writerxml;    try {        //输出        writerxml = new XMLWriter(new FileOutputStream("mm.xml"),format);        writerxml.write(document);            } catch (UnsupportedEncodingException e1) {        // TODO Auto-generated catch block        e1.printStackTrace();    } catch (FileNotFoundException e1) {        // TODO Auto-generated catch block        e1.printStackTrace();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    }}