改变Transformer输出的xml字符编码
在java中,默认的输出字符编码是:UTF-8,即使XML文档与XSL文档的编码都已经设为“GB2312”,transform后的XML仍然是UTF-8。解决方法很简单:通过设置转换器的字符输出编码的系统属性来进行改变。
try
{
TransformerFactory tFactory;
Transformer transformer;
tFactory = TransformerFactory.newInstance();
transformer = tFactory.newTransformer();
//-------- begin
java.util.Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING,"GB2312");
transformer.setOutputProperties(properties);
//------- end
StreamResult result = new StreamResult(out);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
}
catch(javax.xml.transform.TransformerConfigurationException e){e.printStackTrace();}
catch(javax.xml.transform.TransformerException e){e.printStackTrace();}
try
{
TransformerFactory tFactory;
Transformer transformer;
tFactory = TransformerFactory.newInstance();
transformer = tFactory.newTransformer();
//-------- begin
java.util.Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING,"GB2312");
transformer.setOutputProperties(properties);
//------- end
StreamResult result = new StreamResult(out);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
}
catch(javax.xml.transform.TransformerConfigurationException e){e.printStackTrace();}
catch(javax.xml.transform.TransformerException e){e.printStackTrace();}