今天需对一旧系统的功能进行扩展,旧系统使用Castor来操作XML,相应的JavaBean都提供。
而且发现我要用的JavaBeab:DeviceTable提供了 现成的
public void marshal(Writer out) throws ValidationException, MarshalException { }
这样一个函数,于是,代码顺手捏来,
xmlreader = new InputStreamReader(new FileInputStream(xmlfilename));
devicetable = (DeviceTable) Unmarshaller.unmarshal(DeviceTable.class, xmlreader);
和
xmlwriter =new OutputStreamWriter(new FileOutputStream(xmlfilename));
devicetable.marshal(xmlwriter);
可是发现其中的一个属性值中的中文(LabelFont="方正魏碑简体"),在重新生成的XML文件中变成了乱码,而且这个XML文件中的encoding="UTF-8";而原始XML文件中是:encoding="gb2312";
通过跟踪,发现读出来了这个属性是正确的,于是我就怀疑起DeviceTable.marshal()方法了,通过反编译一看,哦:
public void marshal(Writer out)
throws ValidationException, MarshalException {
Marshaller.marshal(this, out);
}
原来这么省,Castor的Marshaller.marshal() 默认“UTF-8”,那就自己来罗,
xmlreader = new InputStreamReader(new FileInputStream(xmlfilename), "gb2312");
devicetable = (DeviceTable) Unmarshaller.unmarshal(DeviceTable.class, xmlreader);
......
xmlwriter =new OutputStreamWriter(new FileOutputStream(xmlfilename), "gb2312");
Marshaller marshaller = new Marshaller(xmlwriter);
marshaller.setEncoding("gb2312"); //关键
marshaller.marshal(devicetable);
哦,OK!