1. 程式人生 > >XML的四種寫入方式

XML的四種寫入方式

ner mls src oms utf-8 gen log 遍歷 return

技術分享

DOM方式生成XML:

技術分享

<?xml version="1.0" encoding="UTF-8"?><bookStore>
<book id="1">
<name>冰與火之歌</name>
<author>喬治馬丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>安徒生童話</name>
<year>2004</year
> <price>77</price> <language>English</language> </book> </bookStore>

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 Demo { /** * 創建DocumentBuilder * @return */ public DocumentBuilder getDocuementBuilder() { // 創建一個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 = getDocuementBuilder(); Document doc = db.newDocument(); // 創建DOM樹 doc.setXmlStandalone(true); // 設置xml文件聲明中的standalone="yes"並不顯示 Element bookstore = doc.createElement("bookStore"); //創建根節點 //向bookstore根節點中添加子節點book //**************************添加第一個book節點*********************************** Element book = doc.createElement("book"); book.setAttribute("id", "1"); // 設置name節點的值並添加到book節點下 Element name = doc.createElement("name"); name.setTextContent("冰與火之歌"); book.appendChild(name); // 設置author節點的值並添加到book節點下 Element author = doc.createElement("author"); author.setTextContent("喬治馬丁"); book.appendChild(author); // 設置year節點的值並添加到book節點下 Element year = doc.createElement("year"); year.setTextContent("2014"); book.appendChild(year); // 設置price節點的值並添加到book節點下 Element price = doc.createElement("price"); price.setTextContent("89"); book.appendChild(price); //將book節點添加到bookstore中 bookstore.appendChild(book); //**************************添加第二個book節點*********************************** // 向bookstore根節點中添加第二個book子節點 Element book2 = doc.createElement("book"); book2.setAttribute("id", "2"); Element name2 = doc.createElement("name"); name2.setTextContent("安徒生童話"); book2.appendChild(name2); Element year2 = doc.createElement("year"); year2.setTextContent("2004"); book2.appendChild(year2); Element price2 = doc.createElement("price"); price2.setTextContent("77"); book2.appendChild(price2); Element language = doc.createElement("language"); language.setTextContent("English"); book2.appendChild(language); bookstore.appendChild(book2); //將根節點bookstore添加到DOM樹中 doc.appendChild(bookstore); //創建TransformerFactory對象 TransformerFactory tff = TransformerFactory.newInstance(); try { //創建Transformer對象 Transformer tf = tff.newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 設置生成的xml文件格式(換行) tf.transform(new DOMSource(doc), new StreamResult(new File("books1.xml"))); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } /** * main */ public static void main(String[] args) { Demo demo = new Demo(); // 調用createXML()方法 demo.createXML(); } }

SAX方式生成XML:

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;



public class SAXParserHandler extends DefaultHandler {
    String value = null;
    Book book = null;
    private ArrayList<Book> bookList = new ArrayList<Book>();
    public ArrayList<Book> getBookList() {
        return bookList;
    }
    int bookIndex = 0;
    /**
     * 用來遍歷xml文件的開始標簽
     */
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        //調用DefaultHandler類的startElement方法
        super.startElement(uri, localName, qName, attributes);
        //開始解析book元素的屬性
        if(qName.equals("book")){
            //創建一個Book對象
            book = new Book();
            bookIndex++;
            //已知book元素下屬性名稱,根據屬性名獲取屬性值
            System.out.println("***********開始遍歷第"+bookIndex+"本書的內容***********");
            /*String value = attributes.getValue("id");
            System.out.println("book的屬性值是:"+value);*/
            int num = attributes.getLength();
            for(int i=0;i<num;i++){
                System.out.print("book元素的第"+(i+1)+"屬性名是:"+attributes.getQName(i));
                System.out.println("==>屬性值是:"+attributes.getValue(i));
                if(attributes.getQName(i).equals("id")){
                    book.setId(attributes.getValue(i));
                }
            }
        }else if(!qName.equals("book") && !qName.equals("bookstore")){
            System.out.print("節點名是:"+qName+"==>");
        }    
    }
    /**
     * 用來遍歷xml文件的結束標簽
     */
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        //調用DefaultHandler類的endElement方法
        super.endElement(uri, localName, qName);
        //判斷是否針對一本書已經遍歷結束
        if(qName.equals("book")){
            bookList.add(book);
            book = null;
            System.out.println("***********結束遍歷第"+bookIndex+"本書的內容***********");
        }else if(qName.equals("name")){
            book.setName(value);
        }else if(qName.equals("author")){
            book.setAuthor(value);
        }else if(qName.equals("year")){
            book.setYear(value);
        }else if(qName.equals("price")){
            book.setPrice(value);
        }else if(qName.equals("language")){
            book.setLanguage(value);
        }
    }
    /**
     * 用來標識解析開始
     */
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("SAX解析開始");
    }
    /**
     * 用來標識解析結束
     */
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("SAX解析結束");
    }
    /**
     * 
     */
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        super.characters(ch, start, length);
        value = new String(ch, start, length);
        if(!value.trim().equals("")){
            System.out.println("節點值是:"+value);
        }
    }
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
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 Demo {
    public ArrayList<Book> parserXML() {
        // 獲取一個SAXParserFactory對象
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // 通過factory獲取SAXParser對象
        SAXParserHandler handler = null;
        try {
            SAXParser parser = factory.newSAXParser();
            // 創建SAXParserHandler對象
            handler = new SAXParserHandler();
            parser.parse("books1.xml", handler);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return handler.getBookList();
    }
    /**
     * 生成XML文件
     */
    public void createXML(){
        ArrayList<Book> bookList = parserXML();
        // 生成xml
        // 1.創建一個SAXTransformerfactory類的對象
        SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        try {
            // 2.通過SAXTransformerFactory對象創建一個TransformerHandler對象
            TransformerHandler handler = tff.newTransformerHandler();
            // 3.通過handler對象創建一個Transformer對象
            Transformer tf = handler.getTransformer();
            // 4.通過Transformer對象對生成的xml文件進行設置
            // 設置xml的編碼格式
            tf.setOutputProperty(OutputKeys.ENCODING, "gb2312");
            // 設置xml“是否換行”
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            // 5.創建一個Result對象
            File file = new File("sax_books.xml");
            if(!file.exists()){
                file.createNewFile();
            }
            // 6.創建Result對象,並且使其與handler關聯
            Result result = new StreamResult(new FileOutputStream(file));
            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", "", "1");
                handler.startElement("", "", "book", attr);
                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");
                }
                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");
                }
                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");
                }
                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");
                }
                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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * main
     */
    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.createXML();
    }    
}

JDOM方式生成XML:

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

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

public class Demo {
    private void createXML(){
        // 1.生成一個根節點
        Element rss = new Element("rss");
        // 2.為節點添加屬性
        rss.setAttribute("version", "2.0");
        // 3.生成一個document對象
        Document doc = new Document(rss);
        Element channel = new Element("channel");
        rss.addContent(channel);
        Element title = new Element("title");
        title.setText("<![CDATA[上海移動互聯網產業促進中心正式揭牌 ]]>");
        
        //CDATA text = new CDATA("<![CDATA[上海移動互聯網產業促進中心正式揭牌 ]]>");
        //title.addContent(text);
        channel.addContent(title);
        Format format = Format.getPrettyFormat();
        //format.setEncoding("UTF-8");
        //設置換行
        format.setIndent("");
        // 4.創建XMLOutputter對象
        XMLOutputter outputter = new XMLOutputter(format);
        try {
            // 5.利用outputter將doc對象轉換成xml文件
            outputter.output(doc, new FileOutputStream(new File("jdom_rssnews.xml")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * main
     */
    public static void main(String[] args) {
        new Demo().createXML();
    }
}

DOM4J方式生成XML:

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

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

public class Demo {
    private void createXML() {
        // 1.創建document對象,代表整個xml文檔
        Document doc = DocumentHelper.createDocument();
        // 2.創建根節點rss
        Element rss = doc.addElement("rss");
        // 3.向rss節點中添加version屬性
        rss.addAttribute("version", "2.0");
        // 4.生成子節點及節點內容
        Element channel = rss.addElement("channel");
        Element title = channel.addElement("title");
        title.setText("<![CDATA[上海移動互聯網產業促進中心正式揭牌 ]]>");
        // 5.設置生成xml文件格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //format.setEncoding("UTF-8");
        // 6.生成xml文件
        File file = new File("dom4j_rssnews.xml");
        XMLWriter writer = null;
        try {
            writer = new XMLWriter(new FileOutputStream(file), format);
            // 設置是否轉義,默認值時true,代表轉義
            writer.setEscapeText(false);
            writer.write(doc);
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * main
     */
    public static void main(String[] args) {
        new Demo().createXML();
    }
}

XML的四種寫入方式