Re: [問題]XML的transform使用?

看板java作者 (22)時間19年前 (2007/01/17 16:52), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《chen.bbs@bbs.cs.pu.edu.tw (小永)》之銘言: : 請問一下各位大大 : 我是用JAVA提供的dom建立的document物件 : 我要如何才能把它轉成XML文件寫入硬碟? : 我查JDK說明文件有提到transform物件 : 但是看不懂~"~ : 有誰可以提供一下範例 : 或是有其它解決的方法? 我這是把一個XML檔案 parse成dom tree 作一些處理 再存回去的程式的一部份 我省掉了處理的部分 這本來是一支jsp 所以沒有一些東西 String path = request.getRealPath("/"); String temp = path + "newXML.xml"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document domTree = parser.parse(temp); -------------以上把檔案建成一個dom tree------------ 下面應該是你問的問題 TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); String newfile = path + "newXML.xml"; DOMSource source = new DOMSource(domTree); File newXML = new File(newfile); FileOutputStream os = new FileOutputStream(newXML); StreamResult result = new StreamResult(os); trans.transform(source, result); -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.118.155.193
文章代碼(AID): #15hUExxL (java)
文章代碼(AID): #15hUExxL (java)