当前位置: 技术问答>java相关
java写xml文件时,如何指定编码格式?(祥见内容)
来源: 互联网 发布时间:2015-05-29
本文导语: 我用下面这段代码写入xml文件 TransformerFactory tFactory =TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new java.io.File("m...
我用下面这段代码写入xml文件
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new java.io.File("menu.xml"));
transformer.transform(source, result);
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new java.io.File("menu.xml"));
transformer.transform(source, result);
|
transformer.setOutputProperty("encoding","GB2312");
or
transformer.setOutputProperty("encoding","GBK");
or
transformer.setOutputProperty("encoding","GBK");
|
//输出XML流
private void outputXML() throws DTreeException {
DOMSource domSource = new DOMSource (doc);
StreamResult streamResult = new StreamResult(this.out);
try {
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING,"gb2312");
properties.setProperty(OutputKeys.VERSION,"1.0");
transformer.setOutputProperties(properties);
transformer.transform(domSource,streamResult);
}
catch (TransformerConfigurationException tce) {
tce.printStackTrace();
throw new DTreeException("TransformerConfigure Exception: "+tce.getMessage());
}
catch (TransformerException te) {
te.printStackTrace ();
throw new DTreeException("Transformer Exception: "+te.getMessage());
}
}
private void outputXML() throws DTreeException {
DOMSource domSource = new DOMSource (doc);
StreamResult streamResult = new StreamResult(this.out);
try {
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING,"gb2312");
properties.setProperty(OutputKeys.VERSION,"1.0");
transformer.setOutputProperties(properties);
transformer.transform(domSource,streamResult);
}
catch (TransformerConfigurationException tce) {
tce.printStackTrace();
throw new DTreeException("TransformerConfigure Exception: "+tce.getMessage());
}
catch (TransformerException te) {
te.printStackTrace ();
throw new DTreeException("Transformer Exception: "+te.getMessage());
}
}