packagedemo;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.StringReader;importjava.util.Date;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.ParserConfigurationException;importjavax.xml.transform.OutputKeys;importjavax.xml.transform.Transformer;importjavax.xml.transform.TransformerFactory;importjavax.xml.transform.dom.DOMSource;importjavax.xml.transform.stream.StreamResult;importorg.w3c.dom.Document;importorg.xml.sax.InputSource;importorg.xml.sax.SAXException;public classDocXml {public static voidmain(String[] args) {
String s1= "<?xml version=\"1.0\" encoding=\"utf-8\"?>
百度
";Document doc=str2Document(s1);
String fileName= "E:\\learn\\a.html";
createXml(fileName, doc);
}public staticDocument str2Document(String xmlStr) {
Document doc= null;
StringReader sr= newStringReader(xmlStr);
InputSource is= newInputSource(sr);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder;try{
builder=factory.newDocumentBuilder();
doc=builder.parse(is);
}catch(ParserConfigurationException e) {
System.out.println("ParserConfiguration错误"+e);
}catch(SAXException e) {
System.out.println("SAX错误"+e);
}catch(IOException e) {
System.out.println("IO错误"+e);
}returndoc;
}public synchronized static voidcreateXml(String fileName, Document document) {
System.out.println("============进入生成xml方法:" + new Date().toLocaleString() + "=================");try{//判断文件是否存在,如存在就删掉它
File file = newFile(fileName);if(file.exists()) {
file.delete();
System.out.println("==============删除xml文件==============");
}/**将document中的内容写入文件中*/TransformerFactory tFactory=TransformerFactory.newInstance();
Transformer transformer=tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
DOMSource source= newDOMSource(document);
StreamResult result= new StreamResult(newFileOutputStream(fileName));
transformer.transform(source, result);
System.out.println("--------------------------------" + "更新 XML文件成功" + "-------------------------------------");
}catch (finalException exception) {
System.out.println("更新" + fileName + "出错:"+exception);
}
System.out.println("============退出生成xml方法:" + new Date().toLocaleString() + "=================");
}
}