C#實(shí)現(xiàn)XML序列化與反序列化
更新時(shí)間:2022年06月06日 10:48:48 作者:springsnow
這篇文章介紹了C#實(shí)現(xiàn)XML序列化與反序列化的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
一、使用 System.Xml.Serialization類
1、定義元數(shù)據(jù)
引入System.Xml.Serialization命名空間。
XML序列化常用屬性:
- XmlRoot
- XmlType
- XmlText
- XmlEnum
[Serializable]
[XmlRoot]
public class Product
{
public int ProductID { set; get; }//默認(rèn)為[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、簡(jiǎn)單序列化與反序列化
//序列化
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, 53、集合的序列化與反序列化
//序列化
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, 54、在不能更改數(shù)據(jù)的情況下,可以用代碼重載 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, 55、通用類
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
{
///
/// 序列化對(duì)象
///
/// 對(duì)象類型
/// 對(duì)象
///
public static string Serialize(T t)
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer xz = new XmlSerializer(t.GetType());
xz.Serialize(sw, t);
return sw.ToString();
}
}
///
/// 反序列化為對(duì)象
///
/// 對(duì)象類型
/// 對(duì)象序列化后的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、層次結(jié)構(gòu)
基類:XmlObjectSerializer
派生類:
- DataContractSerializer
- NetDataContractSerializer
- DataContractJsonSerializer
需要引入的程序集:
- System.Runtime.Serialization.dll
- System.Runtime.Serialization.Primitives.dll
2、實(shí)體類
//訂單類
[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; }
}
//產(chǎn)品類
[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內(nèi)容
<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>到此這篇關(guān)于C#實(shí)現(xiàn)XML序列化與反序列化的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- C#對(duì)Json進(jìn)行序列化和反序列化
- C#中關(guān)于序列化與反序列化的三種方法
- C# 解析XML和反序列化的示例
- C# Newtonsoft.Json 解析多嵌套json 進(jìn)行反序列化的實(shí)例
- C#中Json反序列化的實(shí)現(xiàn)方法
- C#實(shí)現(xiàn)XML與實(shí)體類之間相互轉(zhuǎn)換的方法(序列化與反序列化)
- C#序列化與反序列化(Serialize,Deserialize)實(shí)例詳解
- c#對(duì)象反序列化與對(duì)象序列化示例詳解
- C#實(shí)現(xiàn)json的序列化和反序列化實(shí)例代碼
- 深入理解C#序列化與反序列化的詳解
- C# SimpleJSON字典反序列化實(shí)戰(zhàn)教程
相關(guān)文章
ListView用法中與滾動(dòng)相關(guān)的需求實(shí)現(xiàn)
這篇文章主要介紹了ListView用法中與滾動(dòng)相關(guān)的需求實(shí)現(xiàn),獲取并設(shè)置ListView的滾動(dòng)位置,以及獲取滾動(dòng)位置處的項(xiàng)目,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
解析C#多線程編程中異步多線程的實(shí)現(xiàn)及線程池的使用
這篇文章主要介紹了C#多線程編程中異步多線程的實(shí)現(xiàn)及線程池的使用,同時(shí)對(duì)多線程的一般概念及C#中的線程同步并發(fā)編程作了講解,需要的朋友可以參考下2016-03-03
C#定義并實(shí)現(xiàn)單鏈表實(shí)例解析
這篇文章主要介紹了C#定義并實(shí)現(xiàn)單鏈表實(shí)例解析,有助于讀者加深對(duì)C#實(shí)現(xiàn)數(shù)據(jù)結(jié)構(gòu)的理解,需要的朋友可以參考下2014-07-07
C#中DataTable 轉(zhuǎn)換為 Json的方法匯總(三種方法)
JavaScript Object Notation (Json)是一種輕量級(jí)的數(shù)據(jù)交換格式,下面小編給大家介紹三種方法實(shí)現(xiàn)DataTable轉(zhuǎn)換成 Json 對(duì)象,感興趣的朋友一起看看吧2016-11-11

