//用于序列化和反序列化的实体类
1 [Serializable]
2 public class CellBarcodeList
3 {
4 public string serviceId { get; set; } //若字段未初始化,则不会被序列化
5 public string taskId { get; set; }
6 public string LineCode { get; set; }
7 public string cellQty { get; set; }
//[System.Xml.Serialization.XmlIgnoreAttribute] //序列化时不对此字段进行序列化
8 public List<node> data { get; set; }
9 }
10
11 public class node
12 {
13 public string cellBarCode { get; set; }
14 }
1 /// <summary>
2 /// 将实体类CellBarCodeList序列化为XML
3 /// </summary>
4 /// <param name="cellInformation">需要序列化为XML的实体类</param>
5 /// <returns></returns>
6 public string SerializeToXML(CellBarCodeList cellBarCodeList)
7 {
8 try
9 {
10 //方法一
11 using (MemoryStream stream = new MemoryStream())
12 {
13 XmlTextWriter writer = new XmlTextWriter(stream, null);
14 XmlSerializer xml = new XmlSerializer(cellBarcodeList.GetType());
15 xml.Serialize(writer, cellInformation);
16 writer.Formatting = System.Xml.Formatting.Indented;
17 using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
18 {
19 stream.Position = 0;//设置流的当前位置
20 string xmlString = sr.ReadToEnd();
21 sr.Close();
22 stream.Close();
23 return xmlString;
24 }
25 }
26
27 //方法二
28 using(StringWriter sw = new StringWriter())
29 {
30 XmlSerializer xz = new XmlSerializer (cellBarCodeList.GetType());
31 xz.Serialize(sw,cellBarCodeList);
32 return sw.ToString();
33 }
34 }
35 catch (Exception ex)
36 {
37 return ex.Message;
38 }
39 }
1 /// <summary>
2 /// 将XML反序列化为实体类
3 /// </summary>
4 /// <param name="xmlString">需要反序列化为实体类的XML字符串</param>
5 /// <returns></returns>
6 public string SerializeToEntity(string xmlString)
7 {
8 try
9 {
10 using (StringReader sr = new StringReader(xmlString))
11 {
12 XmlSerializer xmldes = new XmlSerializer(typeof(CellBarcodeList));
13 CellBarcodeList cellBarcodeList = xmldes.Deserialize(sr) as CellBarcodeList;
14 }
15 }
16 catch (Execption ex)
17 {
18 return ex.Message;
19 }
20 }
1 <!--序列化后的XML格式-->
2 <?xml version="1.0" encoding="UTF-8"?>
3 <CellBarcodeList>
4 <serviceId>LP002_Cell</serviceId>
5 <taskId>Accept2019173620123</taskId>
6 <LineCode>MZZZ-72H-11</LineCode>
7 <cellQty>2</cellQty>
8 <data>
9 <node>
10 <cellBarCode>KRL30C08MBSA1151601</cellBarCode>
11 </node>
12 <node>
13 <cellBarCode>KRL30C08MBSA1151602</cellBarCode>
14 </node>
15 </data>
16 </CellBarcodeList>