最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實現(xiàn)XML序列化與反序列化

 更新時間:2022年06月06日 10:48:48   作者:springsnow  
這篇文章介紹了C#實現(xiàn)XML序列化與反序列化的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、使用 System.Xml.Serialization類

1、定義元數(shù)據(jù)

引入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、在不能更改數(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, 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>

到此這篇關于C#實現(xiàn)XML序列化與反序列化的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論

武乡县| 云阳县| 鹰潭市| 舒兰市| 溧水县| 伊吾县| 库尔勒市| 牡丹江市| 苏尼特左旗| 永济市| 元朗区| 昭觉县| 神木县| 扬中市| 太康县| 临高县| 绥阳县| 江西省| 芒康县| 合作市| 寻乌县| 延安市| 乌拉特前旗| 汾阳市| 大竹县| 工布江达县| 休宁县| 洪湖市| 额尔古纳市| 镶黄旗| 司法| 荥阳市| 偏关县| 修武县| 梁山县| 申扎县| 奈曼旗| 沂源县| 卓尼县| 紫金县| 商水县|