码迷,mamicode.com
首页 > 其他好文 > 详细

DOM方式创建XML文件

时间:2017-11-20 23:09:32      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:转换   orm   win   ati   amr   form   hat   templates   []   

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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 CreateXmlDocument {

    public static void main(String[] args) {
        /*获得(文件创建工厂)实例*/
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        try {
            /*获取DocumentBuilder对象,单例模式*/
            DocumentBuilder db=factory.newDocumentBuilder();
            /*The Document interface represents the entire HTML or XML document*/
            Document document=db.newDocument();
            document.setXmlStandalone(true);
            Element bookstore=document.createElement("bookstore");
            Element book=document.createElement("book");
            Element name=document.createElement("name");
            name.setTextContent("华");
            book.setAttribute("id", "1");
            book.appendChild(name);
            document.appendChild(bookstore);
            bookstore.appendChild(book);
            
            /*输出文件到XML中*/
            TransformerFactory transformerFactory=TransformerFactory.newInstance();
            try {
                /*转换器*/
                Transformer tf=transformerFactory.newTransformer();
                
                /**设置输出性质  Provides string constants that can be used to set 
                 * output properties for a Transformer, or to retrieve output
                 *  properties from a Transformer or Templates object. 
                 *  提供字符串常数被用去设置输出属性从转换器中,或者去恢复输出属性从转换器或模版对象中。
                 *  
                 *  */
                tf.setOutputProperty(OutputKeys.INDENT, "yes");
                /*输出文件到XML中*/
                tf.transform(new DOMSource(document),
                        new StreamResult(new File("book2.xml")) );
                
                
            } catch (TransformerConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        } catch (Exception e) {
            
            e.printStackTrace();
        }

    }

}

 

DOM方式创建XML文件

标签:转换   orm   win   ati   amr   form   hat   templates   []   

原文地址:http://www.cnblogs.com/yugeng/p/7868459.html

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