在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
关键知识点序列化常用Attribute讲解说明: [XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=false)] // 当该类为Xml根节点时,以此为根节点名称。 [XmlAttribute("AreaName")] // 表现为Xml节点属性。<... AreaName="..."/> [XmlElementAttribute("AreaId", IsNullable = false)] // 表现为Xml节点。<AreaId>...</AreaId> [XmlArrayAttribute("Areas")] // 表现为Xml层次结构,根为Areas,其所属的每个该集合节点元素名为类名。<Areas><Area ... /><Area ... /></Areas> [XmlElementAttribute("Area", IsNullable = false)] // 表现为水平结构的Xml节点。<Area ... /><Area ... />... [XmlIgnoreAttribute] // 忽略该元素的序列化。 实际案例
类定义: 1) OrderEntity单据类XML里是最顶层的Root节点。 /// <summary> /// 订单信息 /// </summary> [Serializable] [XmlRoot("Document")] public class OrderEntity { [XmlArray("Events"), XmlArrayItem("Event")] public OrderEvent[] Event { get; set; } } 2) OrderEvent单据类型(事件)描述实体 /// <summary> /// 单据类型(事件)描述信息 /// </summary> [Serializable] public class OrderEvent { /// <summary> /// 单据名称 /// </summary> [XmlAttribute("Name")] public string Name { get; set; } /// <summary> /// 库存动作 /// </summary> [XmlAttribute("MainAction")] public string MainAction { get; set; } /// <summary> /// 单据明细项 /// </summary> [XmlArray("DataField"), XmlArrayItem("Data")] public OrderDetail[] details { get; set; } } 3)、数据明细类 /// <summary> /// 单据明细项目 /// </summary> [Serializable] public class OrderDetail { [XmlAttribute("Code")] public string Code { get; set; } [XmlAttribute("Actor")] public string Actor { get; set; } [XmlAttribute("ActDate")] public string ActDate { get; set; } [XmlAttribute("CorpOrderID")] public string CorpOrderID { get; set; } [XmlAttribute("FromCorpID")] public string FromCorpID { get; set; } [XmlAttribute("ToCorpID")] public string ToCorpID { get; set; } [XmlAttribute("OwnerID")] public string OwnerID { get; set; } } 4)序列化的实际代码 #region 初始化订单对象并完成序列化 OrderEntity result_File_Object = new OrderEntity { Event = new OrderEvent[] { new OrderEvent { Name =orderName , MainAction= dt_Event.Rows[0]["MainAction"].ToString(), details = query.Where(d => d.Code!=string.Empty).ToList().ToArray() } } }; Program.SerializerToXML<OrderEntity>(path + "\\" + fileName, result_File_Object); #endregion
/// <summary> /// 把对象序列化成xml文件 /// </summary> /// <typeparam name="T">对象的类</typeparam> /// <param name="outFile">输出的文件和路径</param> /// <param name="t">对象的实例</param> public static void SerializerToXML<T>(string outFile, T t) where T : class { using (System.IO.FileStream fs = new System.IO.FileStream(outFile, System.IO.FileMode.Create)) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer xs = new XmlSerializer(typeof(T)); xs.Serialize(fs, t, ns); fs.Flush(); } }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论