通过DOM方式生成xml文件

若要生成如下结构的xml文件,用java该如何做呢?本文介绍如何使用DOM方式生成xml文件。

xml文件结构

<bookstore>
<book id="1">
<name>小王子name>
book>
bookstore>

实现:

package com.imooc.dom.test;

import java.io.IOException;


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;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomTest {

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

    }

    /**
     * 生成xml
     */
    public void creatXML(){
        DocumentBuilder db=getDocumentBuilder();
        Document document=db.newDocument();
        document.setXmlStandalone(true);
        Element bookstore=document.createElement("bookstore");
        //向bookstore根节点中添加book子节点
        Element book=document.createElement("book");
        //向book节点添加属性
        book.setAttribute("id", "1");
        //向book下添加子节点name
        Element name=document.createElement("name");
        //添加name结点内容
        name.setTextContent("小王子");
        book.appendChild(name);
        //将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("book1.xml"));
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        DomTest dt=new DomTest();
        //dt.parseXML();
        dt.creatXML();
    }

}

注:由于作者在该类中还写了解析方法,未粘贴到本文中,所以导入的包有的未使用

你可能感兴趣的:(java+xml)