Skip to content

Java dom4j 生成XML

发布时间:

  • dom4j生成XML 自己整理,经过测试无bug
js
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.List;

public class testXml2 {
    //XML文件代码
    static String XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<Person>\n" +
            "    <XingMing>王东</XingMing >\n" +
            "    <XingBie>男</XingBie>\n" +
            "    <JiaTingChengYuan>\n" +
            "        <Item>\n" +
            "            <ChengWei>儿子</ChengWei>\n" +
            "            <ChuShengRiQi>199001</ChuShengRiQi>\n" +
            "        </Item>\n" +
            "        <Item>\n" +
            "            <ChengWei>女儿</ChengWei>\n" +
            "            <ChuShengRiQi>199403</ChuShengRiQi>\n" +
            "        </Item>\n" +
            "    </JiaTingChengYuan>\n" +
            "</Person>";

    //生成XML
    public static void createXML() {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("Person");
        Element XingMing = root.addElement("XingMing");
        XingMing.setText("王东");
        Element XingBie = root.addElement("XingBie");
        XingBie.setText("男");
        Element JiaTingChengYuan = root.addElement("JiaTingChengYuan");
        Element  Item =JiaTingChengYuan.addElement("Item");
        Element  ChengWei = Item.addElement("ChengWei");
        ChengWei.setText("儿子");
        Element  ChuShengRiQi = Item.addElement("ChuShengRiQi");
        ChuShengRiQi.setText("199001");
        Element  Item2 =JiaTingChengYuan.addElement("Item");
        Element  ChengWei2 = Item2.addElement("ChengWei");
        ChengWei2.setText("女儿");
        Element  ChuShengRiQi2 = Item2.addElement("ChuShengRiQi");
        ChuShengRiQi2.setText("199403");
       String xml= root.asXML();
       System.out.println(xml);
    }

}