https://bbs.csdn.net/topics/330109997?list=1084714
将XML的Document对象转换为UTF-8编码的字符串时,通过UE查看UTF-8编码的内容时,时不时的会有些中文出现乱码变成其它字,大部分中文是正常的。也不是所有有中文的情况都会出现这样的情况,只有少数情况会出现这样的情况,但也够致命的,因为涉及到多系统交互,对方的系统在收到我发过去带有中文乱码的报文时就会处理报异常了。
刚开始以为是JDOM的问题,但是我换了DOM4J、W3C这两种方式进行转换是一样的效果,网上有些地方说有可能是JDK的问题,这个没有证实,以下是我的部分代码,请知道或曾遇到过这样问题的朋友给个建设:
/*将字符串转换为XML Document的方法*/
public static Document getDocument(String xmlString) throws JDOMException, IOException
{
SAXBuilder builder = new SAXBuilder();
Document anotherDocument = builder.build(new StringReader(xmlString));
return anotherDocument;
}
/*将XML Document转换为字符串的方法*/
public static String toXML(Document xmlDoc, String encoding) throws IOException
{
ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
Format format = Format.getPrettyFormat();
format.setEncoding(encoding);
XMLOutputter docWriter = new XMLOutputter(format);
docWriter.output(xmlDoc, byteRep);
return byteRep.toString();
}
/*获取模板XML Document*/
public static Document getRequestDocumentModel() throws JDOMException, IOException{
Document xmlDoc=null;
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request><Ctrl/><Head/><Body><Asxml/></Body></Request>";
xmlDoc = JDomUtil.getDocument(xmlString);
return xmlDoc;
}
========================================================================================
/*简单测试方法*/
Document xmlDoc = null;
xmlDoc = getRequestDocumentModel();
xmlDoc.getRootElement().getChild("Body").getChild("Asxml").setText("这里塞入中文测试");
xmlString = toXML(xmlDoc,"UTF-8");
到这里时,将xmlString打印出来,放到UE中,以UTF-8编码查询,有时不同的中文就会有乱码,先谢了
在网上搜索这是JDK的问题,如果直接输出的就会出现乱码,这个时候需要用相应的输出包装器包装一下就不会出现乱码了,将TOXML写成如下:
public static String toXML(Document xmlDoc, String encoding) throws IOException
{
ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
PrintWriter out=new PrintWriter(byteRep);//增加输出包装器
Format format = Format.getPrettyFormat();
format.setEncoding(encoding);
XMLOutputter docWriter = new XMLOutputter(format);
try {
docWriter.output(xmlDoc, out);//输出到包装器中
} catch (Exception e) {
}
return byteRep.toString();
}
就OK了