使用apache的xerces方法
OutputFormat format = new OutputFormat( doc ); //Serialize DOM
format.setEncoding("UTF-8");
StringWriter stringOut = new StringWriter(); //Writer will be a String
XMLSerializer serial = new XMLSerializer( stringOut, format );
serial.asDOMSerializer(); // As a DOM Serializer
serial.serialize( doc.getDocumentElement() );
System.out.println( "STRXML = " + stringOut.toString() );
使用sun的方法
Writer writer=new OutputStreamWriter(new FileOutputStream(new File("d:/test2.xml")), "UTF-8");
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tFactory.newTransformer();
//设置XML编码
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
// 将DOM对象转化为DOMSource类对象,该对象表现为转化成别的表达形式的信息容器。
DOMSource source = new DOMSource(doc);
//System.out.print(szFilePath);
// 获得一个StreamResult类对象,该对象是DOM文档转化成的其他形式的文档的容器,可以是XML文件,文本文件,HTML文件。这里为一个XML文件。
StreamResult result = new StreamResult(writer);
// 调用API,将DOM文档转化成XML文件。
transformer.transform(source, result);
} catch (TransformerException ex) {
ex.printStackTrace();
}
没有评论:
发表评论