日期:2014-05-20 浏览次数:20745 次
刚才我随便写了一个写xml的类。。没有你说的情况。。test.xml可以右键也可正常打开 // 测试LZ问题 public static void writeXMLFile() throws Exception { Document document = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory .newDocumentBuilder(); // 下面是建立XML文档内容的过程 document = documentBuilder.newDocument(); Element root = document.createElement("webdisknodes"); // 根元素添加上文档 document.appendChild(root); // 建立node元素,添加到次级根结点 Element resultNode = document.createElement("node"); root.appendChild(resultNode); // name Element method = document.createElement("test"); resultNode.appendChild(method); Text tMethod = document.createTextNode("测试第一个节点"); method.appendChild(tMethod); Element methodArgs = document.createElement("second"); resultNode.appendChild(methodArgs); Text tMethodArgs = document.createTextNode("测试第二个节点"); methodArgs.appendChild(tMethodArgs); TransformerFactory tfactory = TransformerFactory.newInstance(); // 对document对象调用normalize(),去掉xml文档中格式 Transformer transformer = tfactory.newTransformer(); document.normalize(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File("f:/test.xml")); transformer.transform(source, result); System.out.println("success"); }
------解决方案--------------------
TransformerFactory tf = TransformerFactory.newInstance(); OutputStreamWriter pw = null; FileOutputStream fs = null; StreamResult result = null; String strXmlPath="c:/testXML.xml"; try { Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); fs = new FileOutputStream(strXmlPath);//strXmlPath为路径 pw = new OutputStreamWriter(fs,"utf-8"); result = new StreamResult(pw); transformer.transform(source, result); fs.flush(); pw.flush(); fs.close(); pw.close(); } catch (Exception ex) { }finally{ try{ if(null!=fs){ fs.close(); } }catch(Exception ex){ } try{ if(null!=pw){ pw.close(); } }catch(Exception ex){ } } }