C#(4):XML序列化

摘要:
˃////1////使用{XmlSerializerxz=newXmlSerializer;Product=xz.DeserializiesProduct;}反序列化安慰WriteLine//1,53.集合的序列化和反序列化//序列化ListList=newList(){newProduct(){{ProductID=1,DisCount=5},newBookProduct()}{ProductID=1,DisCount=3,ISBN=“aaaa”};Inventoryinversion=newInventory{InventoryItems=list.ToArray()};strings=“”;使用{XmlSerializerxz=newXmlSerializer;xz.Serialize;s=sw.ToString();}Console.WriteLine;//˂?

一、使用 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);

//<?xml version="1.0" encoding="utf-16"?>
//<Product xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Discount="5">
//  <ProductID>1</ProductID>
//</Product>

//反序列化
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<Product> list = new List<Product>(){
    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);

//<?xml version="1.0" encoding="utf-16"?>
//<inv xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
// <allpro>
//    <prod Discount="5">
//     <ProductID>1</ProductID>
//    </prod>
//  <book Discount="3">
//      <ProductID>1</ProductID>
//      <ISBN>aaaa</ISBN>
//    </book>
//  </allpro>
//</inv>

//反序列化
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<Product> list = new List<Product>(){
    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);

//<?xml version="1.0" encoding="utf-16"?>
//<inv xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
//  <product1 Discount="5">
//    <ProductID>1</ProductID>
//  </product1>
//  <book1 Discount="3">
//    <ProductID>1</ProductID>
//    <ISBN>aaaa</ISBN>
//  </book1>

//</inv>


//反序列化
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<Product>(typeof(UserQuery.Product), s);
    Console.WriteLine(product.ProductID.ToString() + ", " + product.DisCount); //1, 5
}
public class SimpleSerializer
{
    /// <summary>
    /// 序列化对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="t">对象</param>
    /// <returns></returns>
    public static string Serialize<T>(T t)
    {
        using (StringWriter sw = new StringWriter())
        {
            XmlSerializer xz = new XmlSerializer(t.GetType());
            xz.Serialize(sw, t);
            return sw.ToString();
        }
    }

    /// <summary>
    /// 反序列化为对象
    /// </summary>
    /// <param name="type">对象类型</param>
    /// <param name="s">对象序列化后的Xml字符串</param>
    /// <returns></returns>
    public static T Deserialize<T>(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#(4):XML序列化》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇(转)对Oracle导出文件错误和DMP文件结构的分析,EXP-00008: 遇到 ORACLE 错误 904 ORA-00904: "MAXSIZE": invalid identifierceres关于图优化问题下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

02_编程规约——集合处理

1.【强制】关于hashCode和equals的处理,必须遵循如下规则 1.1 只要重写equals,就必须重写hashCode。 1.2 因为Set存储的是不重复对象,依据hashCode和equals进行判断,所以Set存储的对象必须重写这两个方法。 1.3 如果自定义对象为Map的键,那么必须重写hashCode和equals。 说明:String重...

iOS--Block的那些事

假设我们熟悉代理递值的话,对代理我们可能又爱有恨!我们先建立模型A页面 push B页面,如果把A页面的值传递到B页面,属性和单例传值可以搞定!但是如果Pop过程中把B页面的值传递到A页面,那就可以用单例或者代理了!说到代理,我们要先声明协议,创建代理,很是麻烦。常常我们传递一个数值需要在两个页面间写很多代码,这些代码改变页面的整体顺序,可读性也打了折扣。...

LinqHelper拓展

public static class LinqHelper { //NHibernate.Hql.Ast.HqlBooleanExpression public static Expression<Func<T, bool>> True<T>() {...

Android之OkHttp详解(非原创)

文章大纲 一、OkHttp简介二、OkHttp简单使用三、OkHttp封装四、项目源码下载 一、OkHttp简介 1. 什么是OkHttp   一般在Java平台上,我们会使用Apache HttpClient作为Http客户端,用于发送 HTTP 请求,并对响应进行处理。比如可以使用http客户端与第三方服务(如SSO服务)进行集成,当然还可以爬取网...

JAVA系列笔记十五之intellj idea

1.intellj idea中maven镜像配置 maven的配置地方如图所示:   maven的配置文件settings.xml存在于两个地方: 安装的地方:${M2_HOME}/conf/settings.xml 用户的目录:${user.home}/.m2/settings.xml 上图所示maven的安装目录为bundle 3,因idea中mav...

【ECMAScript5】ES5基础

一、语法 区分大小写。 变量是弱类型的,可以初始化为任意值,也可以随时改变变量所存数据的类型。 每行结尾的分号可有可无,但是建议加上。 注释 单行注释以双斜杠开头(//) 多行注释以单斜杠和星号开头(/*),以星号和单斜杠结尾(*/) 代码块:用{ } 包起来的 二、变量 使用 var (variable的缩写)运算符声明变量。 可以用一个var...