C#实现XML序列化

目录
  • 一、使用 System.Xml.Serialization类
    • 1、定义元数据
    • 2、简单序列化与反序列化
    • 3、集合的序列化与反序列化
    • 4、在不能更改数据的情况下,可以用代码重载 XmlAttributeOverrides
    • 5、通用类
  • 二、用DataContractSerialize类序列化XML
    • 1、层次结构
    • 2、实体类
    • 3、序列化与反序列化

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

到此这篇关于C#实现XML序列化的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C# XML序列化方法及常用特性总结分析

    本文实例总结了C# XML序列化方法及常用特性.分享给大家供大家参考,具体如下: C#对象XML序列化(一):序列化方法和常用特性 .Net Framework提供了对应的System.Xml.Seriazliation.XmlSerializer负责把对象序列化到XML,和从XML中反序列化为对象.Serializer的使用比较直观,需要多注意的是XML序列化相关的Attribute,怎么把这些attribute应用到我们的对象,以及对象公共属性上面去,生成满足预期格式的XML. 这里列出了最

  • C#使用XML序列化操作菜单的方法

    本文实例讲述了C#使用XML序列化操作菜单的方法.分享给大家供大家参考.具体分析如下: 之前的一篇文章<C#递归读取XML菜单数据的方法>没使用XML序列化来操作菜单,而且发现那还有一个问题,就是在XML菜单的某个菜单节点前加上一些注释代码的就不能读取,现在使用XML序列化后可以很方便的读取,故在此写一写. XML菜单的节点代码如下: 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?>   &l

  • C#实现xml文件反序列化读入数据到object的方法

    本文实例讲述了C#实现xml文件反序列化读入数据到object的方法.分享给大家供大家参考.具体实现方法如下: public static object DeSerializeFromXmlString(System.Type typeToDeserialize, string xmlString) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString); MemoryStream memoryStream = new Mem

  • C#复杂XML反序列化为实体对象两种方式小结

    目录 前言 需要操作的Xml数据 一.通过是手写的方式去定义Xml的实体对象模型类 二.通过Visual Studio自带的生成Xml实体对象模型类 1.首先Ctrl+C复制你需要生成的Xml文档内容 2.找到编辑=>选择性粘贴=>将Xml粘贴为类 3.以下是使用VS自动生成的Xml类 验证两个Xml类是否能够反序列化成功 C# XML基础入门(XML文件内容增删改查清) C#XmlHelper帮助类操作Xml文档的通用方法汇总 .NET中XML序列化和反序列化常用类和用来控制XML序列化的属

  • C#实现Xml序列化与反序列化的方法

    本文实例讲述了C#实现Xml序列化与反序列化的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: /// <summary> /// Xml序列化与反序列化 /// </summary> public class XmlUtil { public static string GetRoot(string xml) {     XmlDocument doc = new XmlDocument();     doc.LoadXml(xml.Replace("

  • 详解 C# 中XML对象的序列化和反序列化

    这一篇主要是用来介绍关于C#中的XML序列化的问题,这个相信大家一定会经常使用它,特别是在WPF中,有时候我们需要将我们后台的数据保存在数据库中,从而在软件下一次启动的时候能够自动去加载这些数据,由于我们的这些Model中字段众多,如果单独进行保存那是不太现实的,这个时候将这些字段序列化成xml字符串并保存在数据库中就是一个不错的选择,当我们需要这些数据的时候我们也可以反过来将其序列化为一些字段,最终达到我们的效果,首先我们来看看是如何实现的? public class XMLUtil {   

  • C# 中对象序列化XML的方法

    今天我们来看一下在C#中对象序列化XML的方法. 不得不说,在这个Json横行的年代,XML虽然式微,但也的确是一股子清流.(个人感觉) 不多说,直接开始. 首先先说怎么用 需要用到的是这两个命名空间(主要) using System.Xml; using System.Xml.Serialization; 然后序列化和反序列化的方式和Json一样.(后面提供封装方法) string result = XmlSerializeHelper.Serialize<test>(new test {

  • C#序列化成XML注意细节

    最常用的序列化是把某个类序列化成二进制文件.但有时我们也会把类序列化成xml文件. 假如有如下一个类 复制代码 代码如下: class Arwen { private Hashtable table = new Hashtable(); private TimeSpan time = new TimeSpan(0, 0, 1); public Hashtable Table { get { return table; } set { table = value; } } public TimeS

  • c#正反序列化XML文件示例(xml序列化)

    复制代码 代码如下: using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Text.RegularExpressions;using System.Xml.Serialization;using System.IO;using System; namespace GlobalTimes.Framework{    /// <summar

  • C#实现复杂XML的序列化与反序列化

    本文以一个实例的形式讲述了C#实现复杂XML的序列化与反序列化的方法.分享给大家供大家参考.具体方法如下: 已知.xml(再此命名default.xml)文件,请将其反序列化到一个实例对象. Default.XML文件如下: <?xml version="1.0" encoding="utf-8" ?> <config> <rules> <rule name="namea"> <params&

  • C#实现XML与实体类之间相互转换的方法(序列化与反序列化)

    本文实例讲述了C#实现XML与实体类之间相互转换的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data; using System.Xml; using System.Xml.Serialization; /// <summary> /// Xml序列化与反序列化 //

  • C#实现对象XML序列化的方法

    本文实例讲述了C#实现对象XML序列化的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: using system; using system.xml; using system.xml.serialization; using system.text; using system.io; public class util {     /// <summary>     /// 对象序列化成 xml string     /// </summary>     p

  • C# 解析XML和反序列化的示例

    本次为了记录开发一个基于webservice接口,去解析对方传送过来的xml字符串.实际使用时遇到的一些问题. 传输过来的xml格式大致如下: <?xml version="1.0" encoding="UTF-8"?> <messages xmlns="http://www.test.com/hit/rhin" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&

  • C#中将xml文件反序列化为实例时采用基类还是派生类的知识点讨论

    基类: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DeserializeTest { public class SettingsBase { private string m_fileName; public string FileName { get { return m_fileName; } set { m_fileName = value;

随机推荐