码迷,mamicode.com
首页 > 编程语言 > 详细

java_對於xml的小總結。

时间:2014-07-13 23:44:28      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   使用   

在java中操作xml文件,需要的是導入dom4j的包。對xml的操作,有下面的步驟比較重要。

1、讀取。

      讀取xml首先要獲取文件路徑,然後使用

         SAXReader r = new SAXReader(); 

         Document document = r.reader(file);//file是路徑。之後是獲取根節點Element root =  document.getRootElement();  。代碼如下:

         InputStream is = null;

         //需要返回的名單      

          List<Student> studentList = new ArrayList<>();
        try{
            //將student.xml讀入內存中
            is = this.getClass().getResourceAsStream("/student.xml");
            //將內存中的student.xml轉化爲一個Document
            Document document = new SAXReader().read(is);
            //獲得這個Document的根節點
            Element root = document.getRootElement();

 

2、寫入.

     先創建一個FileOutPutStream,同時獲得OutPutFormat,創建一個XMLWriter,之後用XMLWriter創建的對象寫出document。代碼如下:

            OutPutStream os = new FileOutputStream("src/node1.xml");

            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            XMLWriter xmlWriter = new XMLWriter(os , format);
            xmlWriter.write(document);

注:上面代碼只是提示作用,不完全正確。如需了解詳細的,可以參考:java_生成xml文件   java_解析xml文件


java_對於xml的小總結。,布布扣,bubuko.com

java_對於xml的小總結。

标签:style   blog   http   java   color   使用   

原文地址:http://www.cnblogs.com/eblly/p/3840412.html

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