天天看點

Dom4j生成xml

Dom4j生成xml

<dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
           
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.*;

/**
 * @author 作者:
 * @date 建立時間2021/6/15 9:00
 */
public class CreateDom4j {

    public static void main(String[] args) {
        //dom4j生成xml方法
        createDom4j(new File("F:\\dom4j.xml"));
    }

    public static void createDom4j(File file) {

        try {
            //建立一個Document執行個體
            Document document = DocumentHelper.createDocument();
            //添加根節點
            Element root = document.addElement("root");
            //在根節點下添加第一個子節點
            Element oneChildElement = root.addElement("person").addAttribute("attr", "root one");
            oneChildElement.addElement("people").addAttribute("attr", "child one").addText("person one child one");
            oneChildElement.addElement("people").addAttribute("attr", "child two").addText("person one child two");
            //在根節點下添加第二個子節點
            Element twoChildElement = root.addElement("person").addAttribute("attr", "root two");
            twoChildElement.addElement("people").addAttribute("attr", "child one").addText("person two child one");
            twoChildElement.addElement("people").addAttribute("attr", "child two").addText("person two child two");
            twoChildElement.addElement("people").addAttribute("attr", "child three").addCDATA("person two child three");

            //xml格式化樣式 預設樣式
            //OutputFormat format = OutputFormat.createPrettyPrint();

            //自定義xml樣式
            OutputFormat format = new OutputFormat();
            format.setIndentSize(2);//行縮進
            format.setNewlines(true);//一個節點為一行
            format.setTrimText(true);//去重空格
            format.setPadText(true);
            format.setNewLineAfterDeclaration(false);//放置xml檔案中第二行為空白行
            //輸出xml檔案
            XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
            writer.write(document);
            System.out.println("dom4j CreateDom4j success!");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
           
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <person attr="root one">
    <people attr="child one">person one child one</people>
    <people attr="child two">person one child two</people>
  </person>
  <person attr="root two">
    <people attr="child one">person two child one</people>
    <people attr="child two">person two child two</people>
    <people attr="child three"><![CDATA[person two child three]]></people>
  </person>
</root>