XML的四种写入方式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML的四种写入方式相关的知识,希望对你有一定的参考价值。

技术分享

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的四种写入方式的主要内容,如果未能解决你的问题,请参考以下文章

XML解析——Java中XML的四种解析方式 [转载]

XML解析——Java中XML的四种解析方式

XML的四种解析方式

XML解析——Java中XML的四种解析方式

XML--Java中的四种常见解析方式--dom

Java中XML的四种解析方式