Java眼中的XML-文件写入

DOM 方式生成 XML 文档

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class CreateXML {

    public DocumentBuilder getDocumentBuilder() {
        // 创建一个DocumentBuilderFactory的对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 创建DocumentBuilder对象
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return db;
    }

    /**
     * 生成xml
     */
    public void createXML() {
        DocumentBuilder db = getDocumentBuilder();
        Document document = db.newDocument();
        document.setXmlStandalone(true);  // 不显示standalone
        Element bookstore = document.createElement("bookStore");
        // 向bookstore根节点中添加子节点book
        Element book = document.createElement("book");
        Element name = document.createElement("name");
        // name.setNodeValue("小王子");   // 行不通
        name.setTextContent("小王子");

        book.appendChild(name);
        book.setAttribute("id", "1");
        // 将book节点添加到bookstore根节点中
        bookstore.appendChild(book);
        // 将bookstore节点(已经包含了book)添加到dom树中
        document.appendChild(bookstore);
        // 创建TransformerFactory对象
        TransformerFactory tff = TransformerFactory.newInstance();
        try {
            // 创建Transformer对象
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            tf.transform(new DOMSource(document), new StreamResult(new File("books1.xml")));
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CreateXML creatXml = new CreateXML();
        creatXml.createXML();
    }
}

通过 SAX 方式生成 XML 文档

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import com.xmlparsing.imooc.entity.Book;

public class SAXTestCreate {

    public void createXML() {
        Book b1 = new Book();
        b1.setId("1");
        b1.setName("冰与火之歌");
        b1.setAuthor("乔治马丁");
        b1.setYear("2014");
        b1.setPrice("89");
        Book b2 = new Book();
        b2.setId("2");
        b2.setName("安徒生童话");
        b2.setAuthor("乔治马丁");
        b2.setYear("2004");
        b2.setPrice("77");
        b2.setLanguage("English");
        ArrayList bookList = new ArrayList();
        bookList.add(b1);
        bookList.add(b2);
        
        // 生成xml
        // 1.创建一个TransformerFactory类的对象
        SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory
                .newInstance();
        try {
            // 2.通过SAXTransformerFactory对象创建一个TransformerHandler对象
            TransformerHandler handler = tff.newTransformerHandler();
/*          
            // 3.通过handler对象创建一个Transformer对象,必须在第6步handler.setResult(result);之前写才会生效
            Transformer tr = handler.getTransformer();
            // 4.通过Transformer对象对生成的xml文件进行设置
            // 设置xml的编码
            tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  // 设置编码
            // 设置xml的“是否换行”
            tr.setOutputProperty(OutputKeys.INDENT, "yes"); // 设置节点换行
*/          
            // 5.创建一个Result对象
            File f = new File("newbooks.xml");
            if (!f.exists()) {  // 不存在则创建
                f.createNewFile();
            }
            // 6.创建Result对象,并且使其与handler关联
            Result result = new StreamResult(new FileOutputStream(f));
            handler.setResult(result);
            // 7.利用handler对象进行xml文件内容的编写
            // 打开document
            handler.startDocument();
            AttributesImpl attr = new AttributesImpl();
            handler.startElement("", "", "bookstore", attr);
            
            for (Book book : bookList) {
                attr.clear();
                attr.addAttribute("", "", "id", "", book.getId());
                handler.startElement("", "", "book", attr);
                // 创建name节点
                if (book.getName() != null && !book.getName().trim().equals("")) {
                    attr.clear();
                    handler.startElement("", "", "name", attr);
                    handler.characters(book.getName().toCharArray(), 0, book
                            .getName().length());
                    handler.endElement("", "", "name");
                }
                // 创建year节点
                if (book.getYear() != null && !book.getYear().trim().equals("")) {
                    attr.clear();
                    handler.startElement("", "", "year", attr);
                    handler.characters(book.getYear().toCharArray(), 0, book
                            .getYear().length());
                    handler.endElement("", "", "year");
                }
                // 创建author节点
                if (book.getAuthor() != null && !book.getAuthor().trim().equals("")) {
                    attr.clear();
                    handler.startElement("", "", "author", attr);
                    handler.characters(book.getAuthor().toCharArray(), 0, book
                            .getAuthor().length());
                    handler.endElement("", "", "author");
                }
                // 创建price节点
                if (book.getPrice() != null && !book.getPrice().trim().equals("")) {
                    attr.clear();
                    handler.startElement("", "", "price", attr);
                    handler.characters(book.getPrice().toCharArray(), 0, book
                            .getPrice().length());
                    handler.endElement("", "", "price");
                }
                // 创建language节点
                if (book.getLanguage() != null && !book.getLanguage().trim().equals("")) {
                    attr.clear();
                    handler.startElement("", "", "language", attr);
                    handler.characters(book.getLanguage().toCharArray(), 0, book
                            .getLanguage().length());
                    handler.endElement("", "", "language");
                }
                handler.endElement("", "", "book");
            }
            handler.endElement("", "", "bookstore");
            
            // 关闭document
            handler.endDocument();

        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SAXTestCreate test = new SAXTestCreate();
        test.createXML();
    }
}

通过 DOM4J 方式生成 XML 文档

生成RSS文件格式的xml文件

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

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

public class DOM4JTestCreate {
    private void createXML() {
        // 1.创建document对象,代表整个xml文档
        Document document = DocumentHelper.createDocument();
        // 2.创建根节点rss
        Element rss = document.addElement("rss");
        // 3.向rss节点中添加version属性
        rss.addAttribute("version", "2.0");
        // 4.生成子节点及节点内容
        Element channel = rss.addElement("channel");
        Element title = channel.addElement("title");
        title.setText("");
        // 5.设置生成xml的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("GBK");
        // 6.生成xml文件
        File file = new File("rssnews.xml");
        XMLWriter writer;
        try {
            writer = new XMLWriter(new FileOutputStream(file), format);
            // 设置是否转义,默认值是true,代表转义
            writer.setEscapeText(false);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new DOM4JTestCreate().createXML();
    }
}

通过 JDOM 方式生成 XML 文档

package com.xmlparsing.imooc.write.jdom;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

public class JDOMTestCreate {

    private void createXML() {
        // 1.生成一个根节点
        Element rss = new Element("rss");
        // 2.为节点添加属性
        rss.setAttribute("version", "2.0");
        // 3.生成一个document对象
        Document document = new Document(rss);

        Element channel = new Element("channel");
        rss.addContent(channel);
        Element title = new Element("title");
        title.setText("");
/*      
        // 解决xml转义的问题
        CDATA cdata = new CDATA("<上海移动互联网产业促进中心正式揭牌>");
        title.addContent(cdata);
*/      
        channel.addContent(title);

        Format format = Format.getCompactFormat();
        format.setIndent("");
        format.setEncoding("GBK");

        // 4.创建XMLOutputter的对象
        XMLOutputter outputer = new XMLOutputter(format);
        try {
            // 5.利用outputer将document对象转换成xml文档
            outputer.output(document, new FileOutputStream(new File("rssnews.xml")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        JDOMTestCreate creater = new JDOMTestCreate();
        creater.createXML();
    }
}

不同生成方法大PK

  • DOM基于Tree
  • SAX基于事件
  • JDOM、DOM4J基于底层API

DOM生成的DOM树会驻留在内存中,方便后期改动,删除、修改、重新排列

SAX不能在写的过程中回头修改

你可能感兴趣的:(Java眼中的XML-文件写入)