xml序列化和反序列化(一)
最近项目中需要调用第三方webservice,入参和出参采用xml格式,大致如下:
入参:
<?xml version="1.0" encoding="utf-8"?>
<RequestParams>
<PatientsName/>
<PatientsID/>
</RequestParams>
出参:
<?xml version="1.0" encoding="utf-8"?>
<PacsResult>
<successe>true</successe>
<msg>成功</msg>
<reports>
<report>
<PatientsSex></PatientsSex>
<PatientsName></PatientsName>
</report>
</reports>
</PacsResult>
关于入参,项目中封装的有入参实体,实体类如下:
public class rep
{
public string PatientsName { get; set; }
public string PatientsID { get; set; }
}
现在就需要怎么将入参实体转换为xml格式字符串,代码如下:
/// <summary> /// 序列化 /// </summary> /// <param name="T">泛型t</param> /// <returns></returns> public static string XmlSerializerSR<T>(T t) { MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(typeof(T)); try { //序列化对象 xml.Serialize(Stream, t); } catch (InvalidOperationException) { throw; } Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; }
测试结果:
<?xml version="1.0"?> <RequestParams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <PatientsName>Cui Jian Hong</PatientsName> <PatientsID>P57748</PatientsID> </RequestParams>
有些人看到觉得这和入参不一样,
<?xml version="1.0"?>少了utf-8,<RequestParams》多了个xmlns(xml命名空间,我这里不作过多介绍)这个玩意;强迫症犯了,要求必须和入参一摸一样,我就尝试用另外一种方法:
public static string XmlSerializerXTW<T>(T t) { using (MemoryStream ms = new MemoryStream()) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); //Add an empty namespace and empty value ns.Add("", ""); XmlTextWriter textWriter = new XmlTextWriter(ms, Encoding.GetEncoding("UTF-8")); //StreamWriter streamWriter = new StreamWriter(ms, Encoding.GetEncoding("utf-8"))效果一样; XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(textWriter, t, ns); string xmlMessage = Encoding.UTF8.GetString(ms.GetBuffer()); xmlMessage = System.Text.RegularExpressions.Regex.Replace(xmlMessage, "^[^<]", ""); ms.Close(); textWriter.Close(); return xmlMessage; } }
看到代码里为什么多了个正则表达式替换呢,原因是因为如果不加这个,序列化后是这样的
?<?xml version="1.0" encoding="utf-8"?> <RequestParams> <PatientsName>Cui Jian Hong</PatientsName> <PatientsID>P57748</PatientsID> </RequestParams>
注意第一个字符,不是粘贴错误,哈哈,实际就是多个问号;蛋疼了,网上找了半天,最后就这么解决了,哪位大神知道为什么,请告之。
写到这里有些人觉得,这么搞有点牵强,不完美,怎么办呢,还有终极杀招,自定义xml,无非就是拼接呗:可以这么搞:
/// <summary> /// 拼接入参 /// </summary> /// <param name="inParams"></param> /// <returns></returns> public static string CreateInParams(Dictionary<string, string> inParams,string inParamName) { string ret = string.Empty; XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); XmlElement xnIn = doc.CreateElement(inParamName); doc.AppendChild(xnIn); foreach (var de in inParams) { XmlElement xn = doc.CreateElement(de.Key); xn.InnerText = de.Value; xnIn.AppendChild(xn); } ret = doc.OuterXml; return ret; }
当然代码里是入参Dictionary<string, string>,不过这个可以任意定义,实体也行,数组也行。。。我这里只提供一个思路。
关于出参解析,请看下篇介绍
上一篇: 虹软人脸识别速度测试征集