C#实现XML序列化与反序列化
作者:springsnow 时间:2022-10-06 19:50:21
一、使用 System.Xml.Serialization类
1、定义元数据
引入System.Xml.Serialization命名空间。
XML序列化常用属性:
XmlRoot
XmlType
XmlText
XmlEnum
[Serializable]
[XmlRoot]
public class Product
{
public int ProductID { set; get; }//默认为[XmlElement("ProductID")]
[XmlAttribute("Discount")]
public int DisCount { set; get; }
}
public class BookProduct : Product
{
public BookProduct() { }
public string ISBN { get; set; }
}
[XmlRoot("inv")]
public class Inventory
{
public Inventory() { }
[XmlArray("allpro")]
[XmlArrayItem("prod", typeof(Product)),
XmlArrayItem("book", typeof(BookProduct))]
public Product[] InventroyItems { set; get; }
}
2、简单序列化与反序列化
//序列化
Product product = new Product() { ProductID = 1, DisCount = 5 };
string s = "";
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(typeof(Product));
xz.Serialize(sw, product);
s = sw.ToString();
}
Console.WriteLine(s);
//
// Discount="5">
// 1
//
//反序列化
using (StringReader sr = new StringReader(s))
{
XmlSerializer xz = new XmlSerializer(typeof(Product));
product = xz.Deserialize(sr) as Product;
}
Console.WriteLine(product .ProductID.ToString() + ", " + product.DisCount); //1, 5
3、集合的序列化与反序列化
//序列化
List list = new List(){
new Product() { ProductID = 1, DisCount =5 },
new BookProduct() { ProductID = 1, DisCount =3, ISBN="aaaa"}
};
Inventory invertoy = new Inventory { InventroyItems = list.ToArray() };
string s = "";
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(typeof(Inventory));
xz.Serialize(sw, invertoy);
s = sw.ToString();
}
Console.WriteLine(s);
//
//
// <allpro>
// <prod Discount="5">
// 1
//
// <book Discount="3">
// 1
// aaaa
//
// allpro>
//
//反序列化
using (StringReader sr = new StringReader(s))
{
XmlSerializer xz = new XmlSerializer(typeof(Inventory));
invertoy = xz.Deserialize(sr) as Inventory;
}
Console.WriteLine(invertoy.InventroyItems[0].ProductID.ToString() + ", " + invertoy.InventroyItems[0].DisCount); //1, 5
4、在不能更改数据的情况下,可以用代码重载 XmlAttributeOverrides
List list = new List(){
new Product() { ProductID = 1, DisCount =5 },
new BookProduct() { ProductID = 1, DisCount =3, ISBN="aaaa"}
};
Inventory invertoy = new Inventory { InventroyItems = list.ToArray() };
string s = "";
//序列化
using (StringWriter sw = new StringWriter())
{
XmlAttributes attrs = new XmlAttributes();
attrs.XmlElements.Add(new XmlElementAttribute("product1", typeof(Product)));
attrs.XmlElements.Add(new XmlElementAttribute("book1", typeof(BookProduct)));
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(Inventory), "InventroyItems", attrs);
XmlSerializer xz = new XmlSerializer(typeof(Inventory), attrOverrides);
xz.Serialize(sw, invertoy);
s = sw.ToString();
}
Console.WriteLine(s);
//
//http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
// <product1 Discount="5">
// 1
//
// <book1 Discount="3">
// 1
// aaaa
//
//
//反序列化
using (StringReader sr = new StringReader(s))
{
XmlAttributes attrs = new XmlAttributes();
attrs.XmlElements.Add(new XmlElementAttribute("product1", typeof(Product)));
attrs.XmlElements.Add(new XmlElementAttribute("book1", typeof(BookProduct)));
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(Inventory), "InventroyItems", attrs);
XmlSerializer xz = new XmlSerializer(typeof(Inventory), attrOverrides);
invertoy = xz.Deserialize(sr) as Inventory;
}
Console.WriteLine(invertoy.InventroyItems[0].ProductID.ToString() + ", " + invertoy.InventroyItems[0].DisCount); //1, 5
5、通用类
void Main()
{
//序列化
Product product = new Product() { ProductID = 1, DisCount = 5 };
string s = UserQuery.SimpleSerializer.Serialize(product);
Console.WriteLine(s);
//反序列化
product = UserQuery.SimpleSerializer.Deserialize(typeof(UserQuery.Product), s);
Console.WriteLine(product.ProductID.ToString() + ", " + product.DisCount); //1, 5
}
public class SimpleSerializer
{
///
/// 序列化对象
///
/// 对象类型
/// 对象
///
public static string Serialize(T t)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(t.GetType());
xz.Serialize(sw, t);
return sw.ToString();
}
}
///
/// 反序列化为对象
///
/// 对象类型
/// 对象序列化后的Xml字符串
///
public static T Deserialize(Type type, string s) where T : class
{
using (StringReader sr = new StringReader(s))
{
XmlSerializer xz = new XmlSerializer(type);
return xz.Deserialize(sr) as T;
}
}
}
二、用DataContractSerialize类序列化XML
1、层次结构
基类:XmlObjectSerializer
派生类:
DataContractSerializer
NetDataContractSerializer
DataContractJsonSerializer
需要引入的程序集:
System.Runtime.Serialization.dll
System.Runtime.Serialization.Primitives.dll
2、实体类
//订单类
[DataContract(Name = "order", Namespace = "http://a/order")]
//[KnownType(typeof(order))]
public class Order
{
public Order(Guid id, Product product)
{
this.OrderID = id;
this.Product = product;
}
[DataMember(Name = "id", Order = 2)]
public Guid OrderID { set; get; }
[DataMember]
public Product Product { set; get; }
}
//产品类
[DataContract(Name = "product", Namespace = "http://a/product")] //IsRequired=false,EmitDefaultValue=false
public class Product
{
public Product(Guid id, string productArea)
{
this.ProductID = id;
this.productArea = productArea;
}
[DataMember(Name = "id", Order = 1)]
public Guid ProductID { set; get; }
[DataMember]
private string productArea { set; get; } //私有属性也可以序列化。
}
3、序列化与反序列化
Product product = new Product(Guid.NewGuid(), "XiaMen");
Order order = new Order(Guid.NewGuid(), product);
string filename = @"C:\s.xml";
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Order));
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs))
{
serializer.WriteObject(writer, order);
}
}
Process.Start(filename);
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Order));
using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()))
{
order = serializer.ReadObject(reader) as Order;
}
}
得到的XML内容
<xml version="1.0" encoding="utf-8"?>
<order xmlns="http://a/order" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Product xmlns:a="http://a/product">
<a:productArea>XiaMen</a:productArea>
<a:id>d3b4c977-d052-4fd4-8f59-272e56d875a8</a:id>
</Product>
<id>96d0bb44-cee4-41b6-ae20-5d801c1b3dc9</id>
</order>
来源:https://www.cnblogs.com/springsnow/p/12884534.html
标签:C#,XML,序列化,反序列化
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android源码 在Ubuntu上下载,编译和安装
2022-11-28 14:31:29
![](https://img.aspxhome.com/file/2023/7/139057_0s.jpg)
java中StopWatch的使用详解
2023-12-21 03:19:04
详解SpringMVC常用注解功能及属性
2021-12-29 02:49:23
C#如何解析http报文
2022-11-22 23:20:56
![](https://img.aspxhome.com/file/2023/6/85696_0s.png)
C#实现彻底删除文件的方法
2022-06-25 22:40:29
![](https://img.aspxhome.com/file/2023/8/102278_0s.jpg)
java 面试题闰年判断详解及实例
2023-11-27 19:09:01
idea中MavenWeb项目不能创建Servlet的解决方案
2022-07-09 19:26:11
![](https://img.aspxhome.com/file/2023/0/121960_0s.jpg)
在C#中根据HardwareID获取驱动程序信息的实现代码
2023-08-04 08:15:31
JAVA生成短8位UUID的实例讲解
2021-08-21 04:26:19
快速理解Java设计模式中的组合模式
2021-10-18 04:16:29
![](https://img.aspxhome.com/file/2023/3/86733_0s.jpg)
深入c# 类和结构的区别总结详解
2023-01-25 10:27:27
Android AIDL实现跨进程通信的示例代码
2023-10-07 07:35:10
Java源码解析HashMap成员变量
2023-04-24 07:20:22
Android Application的使用全面解析
2023-08-26 04:23:49
![](https://img.aspxhome.com/file/2023/0/137520_0s.png)
Android应用启动白屏处理方案详解
2022-06-24 23:09:18
Spring boot + mybatis + Vue.js + ElementUI 实现数据的增删改查实例代码(一)
2021-12-29 08:15:07
![](https://img.aspxhome.com/file/2023/5/65725_0s.jpg)
java中的SpringBoot框架
2022-02-10 16:50:05
Android互联网访问图片并在客户端显示的方法
2021-12-26 21:25:10
![](https://img.aspxhome.com/file/2023/1/138341_0s.jpg)
Android后台线程和UI线程通讯实例
2023-04-20 23:01:19
基于spring AOP @Around @Before @After的区别说明
2023-12-15 03:08:25
![](https://img.aspxhome.com/file/2023/6/81966_0s.jpg)