1 简介

java生成xml的4种方法有DOM、SAX、JDOM、DOM4J。

DOM是基于DOM树结构,构造DOM树后开始进行相关工作。使用较简单,但很繁。支持对xml文档随机操作;消耗内存。

SAX类似流媒体,基于事件驱动,有点面向xml编程的感觉。一步步,每步不能后退。内存消耗较少,无法修改操作。

JDOM和DOM4J都是基于底层API进行开发操作,需要导入jar包。

整体来说,推荐使用DOM4J

2.1 DOM方法写入

package xml.write;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class WriteXmlByDom {
    public void createCompanyXml() throws Exception {
        // DocumentBuilderFactory是工厂类,不能直接实例化,
        // 该类包含newInstance()方法,可以根据系统默认的解析器
        // 生成创建解析器的工厂类.
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // 生成相应的DOM解析器
        DocumentBuilder builder = factory.newDocumentBuilder();
        // 获取document对象,然后就可以根据个人需求生成xml文件
        Document doc = builder.newDocument();
        String fileName = "company.xml";
        initXml(fileName, doc);
    }

    public void initXml(String fileName, Document doc) throws Exception {
        // 先建立节点,再添加节点,称为公司
        Element company = doc.createElement("company");
        doc.appendChild(company);
        // 再建立次节点,再添加节点,称为money部门
        Element moneyApartment = doc.createElement("apartment");
        moneyApartment.setAttribute("id","1");
        company.appendChild(moneyApartment);
        // 建立三次节点,新增部门下的员工
        Element staff001 = doc.createElement("staff");
        staff001.setAttribute("id", "001");
        moneyApartment.appendChild(staff001);
        // 增加该员工的属性
        Element staff001Name = doc.createElement("name");
        staff001Name.setTextContent("001老大");
        staff001.appendChild(staff001Name);
        Element staff001Age = doc.createElement("age");
        staff001Age.setTextContent("40");
        staff001.appendChild(staff001Age);
        // 再加一个部门,为person部门
        Element personApartment = doc.createElement("apartment");
        personApartment.setAttribute("id","2");
        company.appendChild(personApartment);
        // 建立三次节点,新增部门下的员工
        Element staff002 = doc.createElement("staff");
        staff002.setAttribute("id", "002");
        personApartment.appendChild(staff002);
        // 增加该员工的属性
        Element staff002Name = doc.createElement("name");
        staff002Name.setTextContent("002老大");
        staff002.appendChild(staff002Name);
        Element staff002Age = doc.createElement("age");
        staff002Age.setTextContent("50");
        staff002.appendChild(staff002Age);

        // 生成xml文档
        // 创建TransformerFactory对象
        TransformerFactory factory = TransformerFactory.newInstance();
        // 创建 Transformer对象
        Transformer transform = factory.newTransformer();
        // 输出内容换行
        transform.setOutputProperty(OutputKeys.INDENT, "yes");
        // 创建xml文件并写入内容
        transform.transform(new DOMSource(doc), new StreamResult(new File(fileName)));
    }

    public static void main(String[] args) throws Exception{
        new WriteXmlByDom().createCompanyXml();
    }
}

效果如下:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
    <apartment id="1">
        <staff id="001">
            <name>001老大</name>
            <age>40</age>
        </staff>
    </apartment>
    <apartment id="2">
        <staff id="002">
            <name>002老大</name>
            <age>50</age>
        </staff>
    </apartment>
</company>

这么说吧,就写这几行xml,写得我已经很烦了。每一个节点的每一个属性特征都要一步步来。

2.2 DOM4J方法

package xml.write;

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.File;
import java.io.FileOutputStream;

public class WriteXmlByDOM4J {
    public void createCompanyXml() throws Exception {
        Document doc = DocumentHelper.createDocument();
        Element company = doc.addElement("company");//添加公司
        Element moneyApartment = company.addElement("apartment");//添加部门
        moneyApartment.addAttribute("id","1");
        Element staff001 = moneyApartment.addElement("staff");//添加员工
        staff001.addAttribute("id","001");
        Element staff001Name = staff001.addElement("name");//添加姓名
        staff001Name.setText("001老大");
        Element staff001Age = staff001.addElement("age");//添加年龄
        staff001Age.setText("40");

        Element personApartment = company.addElement("apartment");//添加部门
        personApartment.addAttribute("id","2");
        Element staff002 = personApartment.addElement("staff");//添加员工
        staff002.addAttribute("id","002");
        Element staff002Name = staff002.addElement("name");//添加姓名
        staff002Name.setText("002老大");
        Element staff002Age = staff002.addElement("age");//添加年龄
        staff002Age.setText("50");

        //写入xml文档
        OutputFormat format = OutputFormat.createPrettyPrint();//写入xml文档
        format.setEncoding("UTF-8");// 设置编码格式
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File("company2.xml")), format);
        xmlWriter.write(doc);
        xmlWriter.close();
    }

    public static void main(String[] args) throws Exception{
        new WriteXmlByDOM4J().createCompanyXml();
    }
}

相对简洁很多

效果如下

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

<company>
  <apartment id="1">
    <staff id="001">
      <name>001老大</name>
      <age>40</age>
    </staff>
  </apartment>
  <apartment id="2">
    <staff id="002">
      <name>002老大</name>
      <age>50</age>
    </staff>
  </apartment>
</company>

2.3 JDOM方法

package xml.write;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.File;
import java.io.FileOutputStream;

public class WriteXmlByJDOM {
    public void createCompany3Xml() throws Exception {
        Element company = new Element("company");
        Document document = new Document(company);
        Element moneyApartment= new Element("apartment");//添加部门
        moneyApartment.setAttribute("id","1");
        company.addContent(moneyApartment);
        Element staff001 = new Element("staff");//添加员工
        staff001.setAttribute("id", "001");
        moneyApartment.addContent(staff001);
        Element staff001Name = new Element("name");//添加姓名
        staff001Name.setText("001老大");
        staff001.addContent(staff001Name);
        Element staff001Age = new Element("age");//添加年龄
        staff001Age.setText("40");
        staff001.addContent(staff001Age);

        Element personApartment= new Element("apartment");//添加部门
        personApartment.setAttribute("id","2");
        company.addContent(personApartment);
        Element staff002 = new Element("staff");//添加员工
        staff002.setAttribute("id", "002");
        personApartment.addContent(staff002);
        Element staff002Name = new Element("name");//添加姓名
        staff002Name.setText("002老大");
        staff002.addContent(staff002Name);
        Element staff002Age = new Element("age");//添加年龄
        staff002Age.setText("50");
        staff002.addContent(staff002Age);

        //生成xml
        Format format = Format.getPrettyFormat();
        XMLOutputter out = new XMLOutputter(format);
        out.output(document, new FileOutputStream(new File("company3.xml")));
    }

    public static void main(String[] args) throws Exception{
        new WriteXmlByJDOM().createCompany3Xml();
    }
}

效果图如下:

<?xml version="1.0" encoding="UTF-8"?>
<company>
    <apartment id="1">
        <staff id="001">
            <name>001老大</name>
            <age>40</age>
        </staff>
    </apartment>
    <apartment id="2">
        <staff id="002">
            <name>002老大</name>
            <age>50</age>
        </staff>
    </apartment>
</company>

2.4 SAX方法

package xml.write;

import org.xml.sax.helpers.AttributesImpl;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.util.jar.Attributes;

public class WriteXmlBySAX {
    public void createCompanyXml() throws Exception{
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = factory.newTransformerHandler();
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Result result = new StreamResult(new FileOutputStream(new File("company4.xml")));
        handler.setResult(result);
        AttributesImpl attr = new AttributesImpl();

        //开始document写入
        handler.startDocument();
        handler.startElement("","","company",attr);//写入公司

        //开始写moneyApartment
        attr.clear();
        attr.addAttribute("","","id","","1");
        handler.startElement("","","apartment",attr);//写入部门

        attr.clear();
        attr.addAttribute("","","id","","001");
        handler.startElement("","","staff",attr);//写入员工

        attr.clear();
        handler.startElement("","","name",attr);//写入姓名
        handler.characters("001老大".toCharArray(), 0, "001老大".toCharArray().length);
        handler.endElement("","","name");

        attr.clear();
        handler.startElement("","","age",attr);
        handler.characters("40".toCharArray(), 0, "40".toCharArray().length);
        handler.endElement("","","age");

        handler.endElement("","","staff");
        handler.endElement("","","apartment");

        //开始写personApartment
        attr.clear();
        attr.addAttribute("","","id","","2");
        handler.startElement("","","apartment",attr);//写入部门

        attr.clear();
        attr.addAttribute("","","id","","002");
        handler.startElement("","","staff",attr);//写入员工

        attr.clear();
        handler.startElement("","","name",attr);//写入姓名
        handler.characters("002老大".toCharArray(), 0, "002老大".toCharArray().length);
        handler.endElement("","","name");

        attr.clear();
        handler.startElement("","","age",attr);
        handler.characters("50".toCharArray(), 0, "50".toCharArray().length);
        handler.endElement("","","age");

        handler.endElement("","","staff");
        handler.endElement("","","apartment");
        handler.endElement("","","company");

        handler.endDocument();
    }

    public static void  main(String[] args) throws Exception{
        new WriteXmlBySAX().createCompanyXml();
    }
}

效果如下

<?xml version="1.0" encoding="UTF-8"?>
<company>
    <apartment id="1">
        <staff id="001">
            <name>001老大</name>
            <age>40</age>
        </staff>
    </apartment>
    <apartment id="2">
        <staff id="002">
            <name>002老大</name>
            <age>50</age>
        </staff>
    </apartment>
</company>