最近做一个项目,是java提供webservice供.net调用。参数采用xml格式。
首先碰到的问题:
1).net这边采用XmlSerializer 方式序列化对象传递给对方。对方在本机调试可以收到,但是部署到本机或者服务器上就无法接收,具体是<?xml前面多了个?.
怀疑是java那边的编码问题,一直让他们协助解决。无解,他们采用java的fxt框架,接收的字符串就是那样了。
2)那只能通过.net的编码问题解决,采用纯文本的xml格式,java那边能正常接收。
3)
XmlSerializer serializer = new XmlSerializer(typeof(T)); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { XmlWriter writer = new XmlTextWriter(stream, Encoding.UTF8); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", "");//不输出xmlns serializer.Serialize(writer, obj, ns); stream.Position = 0; byte[] buf = new byte[stream.Length]; stream.Read(buf, 0, buf.Length); //result = Convert.ToBase64String(buf); result = System.Text.Encoding.UTF8.GetString(buf); }
更改上面的
XmlTextWriter的encoding为default或Gb312,java那边可以正常接收。但是xml格式的encoding变为gb2312,不符合要求。后来看到找到http://blog.csdn.net/dancefire/article/details/1912345 看到"这回输出就正常了。这里需要注意的是Encoding那一行,这是设置Encoding不要输出BOM,否则生成的字符串前会有几个字节表示Byte Order。"
关于BOM,请参考:
Byte Order Mark (BOM) FAQ
http://unicode.org/faq/utf_bom.html#BOM
Byte-order mark (wikipedia)
http://en.wikipedia.org/wiki/Byte_Order_Mark
说明的道理就是我现在碰到的问题。依照他的方法,问题解决。代码如下:
using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { XmlWriterSettings setting = new XmlWriterSettings(); setting.Encoding = new UTF8Encoding(false); setting.Indent = true; XmlWriter writer =XmlWriter.Create(stream, setting); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", "");//不输出xmlns serializer.Serialize(writer, obj, ns); stream.Position = 0; byte[] buf = new byte[stream.Length]; stream.Read(buf, 0, buf.Length); //result = Convert.ToBase64String(buf); result = System.Text.Encoding.UTF8.GetString(buf); }
时间: 2024-11-08 23:14:41