DOM4J生成XML

创建Document 对象,代表整个 XML 文档

//创建Document 对象,代表整个 xml文档
Document document = DocumentHelper.createDocument();

创建根节点

//创建根节点
Element school = document.addElement("school");

创建子节点以及子节点的属性和属性值

//创建子节点
Element student = school.addElement("student"); 
//子节点的属性
student.addAttribute("id", "1");

创建 student下的子节点以及添加内容

//创建 student下的子节点
Element name = student.addElement("name");
//添加内容
name.setText("张三");

 自动格式话 XML 文件

//自动格式化xml 文件
OutputFormat format = OutputFormat.createPrettyPrint();

创建 XML 文件

//创建 XML 文件
File file =new File("DOM4JXML.xml");

XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);
//特殊字符,是否转义,默认为true
writer.setEscapeText(false);
writer.write(document);
writer.close();

运行结果:

<?xml version="1.0" encoding="UTF-8"?>

<school>
  <student id="1">
    <name>张三</name>
  </student>
</scho

完整代码:

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

  public class createDOM4JTest {

    public static void main(String[] args) {
        //创建Document 对象,代表整个 xml文档
        Document document = DocumentHelper.createDocument();
        //创建根节点
        Element school = document.addElement("school");
        
        //创建子节点
        Element student = school.addElement("student"); 
        //子节点的属性
        student.addAttribute("id", "1");
        //创建 student下的子节点
        Element name = student.addElement("name");
        //添加内容
        name.setText("张三");
        
        //自动格式化xml 文件
        OutputFormat format = OutputFormat.createPrettyPrint();
        //创建 XML 文件
        File file =new File("DOM4JXML.xml");
        //XMLWriter writer;
        try {
            XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);
            //特殊字符,是否转义,默认为true
            writer.setEscapeText(false);
            writer.write(document);
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}

 

 posted on 2017-11-16 15:08  【邵江】  阅读(1738)  评论(1编辑  收藏  举报