前言
系统要求能够回复微信用户发过来的文本消息。实现中使用的实体对象进行XML的序列化的方式来实现XML消息。
微信平台的回复例子
这是我测试成功后的例子
如果简单使用xml serializer会包括两个部分,就是下面第一行和第二行
<?xml version="1.0" encoding="utf-16"?><xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><FromUserName>test</FromUserName><CreateTime>0</CreateTime><MsgId>0</MsgId></xml>
由于下面的两行发送给微信服务器,微信服务器会报错,因此必须要移除第一行和去掉xmlns 命名空间的字符串
<?xml version="1.0" encoding="utf-16"?><xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
最开始想简单用字串替换的方式,后来还是老老实实的用标准方法来做。给出一个完整的例子吧,拷贝吧!
public class WebChatXmlMessageSerializer : ISerializer{public string SerializeToXML(Object obj){string outXML = string.Empty;if (obj == null)return outXML;XmlSerializer xs = new XmlSerializer(obj.GetType(),new XmlRootAttribute("xml"));//namsepaces is emty//to remove xmlns <xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {new XmlQualifiedName(string.Empty, string.Empty) // Default Namespace});// I‘ll use a MemoryStream as my backing store.using (MemoryStream ms = new MemoryStream()){// This is extra! If you want to change the settings for the XmlSerializer, you have to create// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.// So, in this case, I want to omit the XML declaration.XmlWriterSettings xws = new XmlWriterSettings();xws.OmitXmlDeclaration = true;xws.Encoding = Encoding.UTF8; // This is probably the default//equal writer.Formatting = Formatting.Indented;xws.Indent = true;var xwr = XmlTextWriter.Create(ms, xws);// remove <?xml header
//http://*.com/questions/7913798/xmlserializer-to-xelementms.Position = 0;xs.Serialize(xwr, obj, namespaces);outXML = System.Text.Encoding.UTF8.GetString(ms.ToArray());}return outXML;}public T DeSeriralze<T>(string xmlStr){XmlSerializer xmS = new XmlSerializer(typeof(T));object recoveryObject = null;StringReader sr = null;try{sr = new StringReader(xmlStr);//默认用UTF-8打开文件recoveryObject = xmS.Deserialize(sr);}catch (Exception ex){throw ex;}finally{if (sr != null)sr.Close();}return (T)recoveryObject;}}
重点我标记如下:
Enjoy it!