[java]将操作xml对象的结果写到文件里

今天用基于w3c dom操作的方式处理了一些xml文件,其中为"为什么原始的xml文件没有变化?"这个问题纳闷了好久,后来豁然明白,前面的操作都在内存里进行的,与原始生成Document对象的xml文件没有直接关系。因此必须想个办法将操作写会到xml文件中。网上搜到的方法,可以用javax.xml.transform中的内容来完成这个任务。

下面是一些关键代码:

     // write back to the xml file
        DOMSource ds = new DOMSource(doc);   // doc is a Document object
        StreamResult sr = new StreamResult(file);  // file is a File object corresponding to the xml file you want to write to.
        try {
            TransformerFactory.newInstance().newTransformer().transform(ds, sr);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

-----------------------------

public class DOMSource
extends Object

implements Source

Constructor:
DOMSource(Node n)
---Create a new input source with a DOM node.

-----------------------------

SteamResult:

Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.

-------------------------------

 

 

posted @ 2013-04-16 22:49  orchid  阅读(456)  评论(0编辑  收藏  举报