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

将生成的xnl文件输出到文件中

时间:2016-01-14 18:45:28      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

代码:

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 DOMdemo2 {

    public static void main(String[] args) {
        //(1)建立DocumentBuilderFactory,以取到DocumentBuilder
      DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
      DocumentBuilder builder=null;
      
      try {
        //(2)通过DocumentBuilderFactory取得DocumentBuilder
        builder=factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
      //(3)定义Document的接口对象,通过DocumentBuilder进行DOM树的转换操作
      Document doc=null;
      doc=builder.newDocument();
      //(4)建立各个操作节点
      Element addresslist=doc.createElement("addresslist");
      Element linkman=doc.createElement("linkman");
      Element name=doc.createElement("name");
      Element email=doc.createElement("email");
      //(5)设置节点的文本内容
      name.appendChild(doc.createTextNode("张华"));
      linkman.appendChild(doc.createTextNode("sfasf@163.com"));
      //(6)设置节点关系
      linkman.appendChild(name);
      linkman.appendChild(email);
      
      addresslist.appendChild(linkman);
      doc.appendChild(addresslist);
      //(7)输出文档到文件中
      TransformerFactory tf=TransformerFactory.newInstance();
      Transformer t=null;
      try {
         t=tf.newTransformer();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
       t.setOutputProperty(OutputKeys.ENCODING,"UTF-8");//设置编码
       DOMSource source=new DOMSource(doc);//输出文档
       StreamResult result=new StreamResult(new File("D:"+File.separator+"Output.xml"));//指定输出位置
       try {
        t.transform(source, result);//输出
    } catch (TransformerException e) {
        e.printStackTrace();
    }
    }

}

运行结果:

技术分享

将生成的xnl文件输出到文件中

标签:

原文地址:http://www.cnblogs.com/gugibv/p/5130986.html

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