码迷,mamicode.com
首页 > 编程语言 > 详细

Java生成XML文件

时间:2017-01-24 00:00:37      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:etc   odi   auto   attribute   gbk   其他   lan   生成xml   learn   

Java眼中的XML ---文件写入

四种方法用Java生成一个XML文件。

1.通过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 DomCreateTest {
    
    public void createXML() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            // XML文件中第一行StandAlone表示该XML文件是否独立设置为yes为默认值  且不显示
            // 表示独立没有外部文件为其服务  设置为no表示外部有其他文件为其服务
            document.setXmlStandalone(true);
            Element bookStore = document.createElement("bookStore");
            Element book = document.createElement("book");
            Element title = document.createElement("title");
            Element author = document.createElement("author");
            title.setTextContent("全职高手");
            author.setTextContent("蝴蝶蓝");
            
            book.appendChild(title);
            book.appendChild(author);
            book.setAttribute("category", "e-sports");
            bookStore.appendChild(book);
            
            document.appendChild(bookStore);
            // 上面已经建好dom树  要将dom树转为xml文本
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer transformer = tff.newTransformer();
            // 生成的xml文件格式  换行
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(new DOMSource(document), new StreamResult(new File("books.xml")));
            
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        new DomCreateTest().createXML();
    }
    
}
DomCreateTest.java

 

2.通过 SAX 方式生成 XML 文档

技术分享
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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;

public class SAXCreateTest {
    public void createXML() {
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        try {
            TransformerHandler handler = factory.newTransformerHandler();
            Transformer transformer = handler.getTransformer();
            // 设置字符编码
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            // 设置换行
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            File file = new File("books.xml");
            if (!file.exists()) file.createNewFile();
            
            // 创建Result对象 
            Result result = new StreamResult(new FileOutputStream(file));
            // 和Handler对象相关联
            handler.setResult(result);
            // 利用handler对XML文件内容进行编写
            // 打开document
            handler.startDocument();
            // 如果没有属性就直接new就可以了
            AttributesImpl attr = new AttributesImpl();
            handler.startElement("", "", "bookStore", attr);
            
            attr.clear(); 
            attr.addAttribute("", "", "category", "", "e-sports");
            handler.startElement("", "", "book", attr);
            
            attr.clear();
            handler.startElement("", "", "title", attr);
            handler.characters("全职高手".toCharArray(), 0, "全职高手".length());
            handler.endElement("", "", "title");
            
            attr.clear();
            handler.startElement("", "", "author", attr);
            handler.characters("蝴蝶蓝".toCharArray(), 0, "蝴蝶蓝".length());
            handler.endElement("", "", "author");
            
            handler.endElement("", "", "book");
            
            handler.endElement("", "", "bookStore");
            
            handler.endDocument();
            
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        new SAXCreateTest().createXML();
    }
}
SAXCreateTest.java

 

3.通过 DOM4J 方式生成 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 DOM4JCraeteTest {
    
    public void create() {
        Document document = DocumentHelper.createDocument();
        Element bookStore = document.addElement("bookStore");
        
        Element book = bookStore.addElement("book");
        book.addAttribute("category", "e-sport");
        
        Element title = book.addElement("title");
        title.addText("全职高手");
        Element author = book.addElement("author");
        author.addText("蝴蝶蓝");
        // 设置格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        File file = new File("books.xml");
        XMLWriter writer = null;
        // 设置是否转义  默认为true
        
        try {
            writer = new XMLWriter(new FileOutputStream(file), format);
            writer.setEscapeText(false);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    
    public static void main(String[] args) {
        new DOM4JCraeteTest().create();
    }
}
DOM4JCraeteTest.java

 

4.通过 JDOM 方式生成 XML 文档

技术分享
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 JDOMCreateTest {
    
    public void create() {
        Element bookStore = new Element("bookStore");
        Document document = new Document(bookStore);
        
        Element book = new Element("book");
        bookStore.addContent(book);
        book.setAttribute("category", "e-sport");
        
        Element title = new Element("title");
        title.setText("全职高手");
        book.addContent(title);
        
        Element author = new Element("author");
        book.addContent(author);
        
        Format format = Format.getCompactFormat();
        format.setIndent("    ");
        format.setEncoding("GBK");
        
        XMLOutputter outputter = new XMLOutputter(format);
        try {
            outputter.output(document, new FileOutputStream(new File("books.xml")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    public static void main(String[] args) {
        new JDOMCreateTest().create();
    }
}
JDOMCreateTest.java

 

生成文件效果

<?xml version="1.0" encoding="GBK"?>
<bookStore>
    <book category="e-sport">
        <title>全职高手</title>
        <author />
    </book>
</bookStore>

 

Java生成XML文件

标签:etc   odi   auto   attribute   gbk   其他   lan   生成xml   learn   

原文地址:http://www.cnblogs.com/wenruo/p/6345122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!