C# 二进制序列化(BinaryFormatter),Xml序列化(XmlSerializer),自己模拟写一个Xml序列化过程。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization; namespace 序列化
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
Person p = new Person();
p.Name ="张三";
p.Age =;
p.Gender = true; using (System.IO.FileStream file = new FileStream("person.dat", FileMode.Create, FileAccess.Write))
{
//System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter b = new BinaryFormatter();
b.Serialize(file, p); //序列化
}
MessageBox.Show("ok");
} private void button2_Click(object sender, EventArgs e)
{
using (System.IO.FileStream file = new FileStream("person.dat", FileMode.Open, FileAccess.Read))
{
BinaryFormatter b = new BinaryFormatter();
Person p = (Person)b.Deserialize(file); //反序列化 MessageBox.Show(p.Name);
}
} private void button3_Click(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
Person p = new Person();
p.Name = "张三";
p.Age = ;
p.Gender = true;
Person p2 = new Person();
p2.Name = "李四";
p2.Age = ;
p2.Gender = true; list.Add(p);
list.Add(p2); //将Person类对象序列化写入流中
using (System.IO.FileStream file = File.OpenWrite("person.xml"))
{
//System.Xml.Serialization;
XmlSerializer xmlSer = new XmlSerializer(typeof(Person));
xmlSer.Serialize(file, p);
} //也可以将List集合对象序列化写入到流中,对象是Object类型。
using (System.IO.FileStream file = File.OpenWrite("personList.xml"))
{
XmlSerializer xmlSer = new XmlSerializer(typeof(List<Person>)); //通过反射指定类型
xmlSer.Serialize(file, list);
} MessageBox.Show("ok");
} private void button4_Click(object sender, EventArgs e)
{
//Xml反序列化
using (System.IO.FileStream file = File.OpenRead("person.xml"))
{
XmlSerializer xmlSer = new XmlSerializer(typeof(Person));
Person p = (Person)xmlSer.Deserialize(file);
MessageBox.Show(p.Name);
}
}
}
//程序集“序列化, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类型“序列化.Person”未标记为可序列化。
[Serializable] //Serializable 可以被序列化,此类不能被继承。 //XML序列化中不需要此方法!
public class Person
{
private string name;
private int age;
private bool gender; [XmlIgnore] //XmlIgnoreAttribute 不序列化公共字段或公共读写属性值。
public bool Gender
{
get { return gender; }
set { gender = value; }
} public int Age
{
get { return age; }
set { age = value; }
} public string Name
{
get { return name; }
set { name = value; }
} }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization; namespace 序列化
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
MyPerson mp = new MyPerson();
mp.Name = "张三";
mp.Age = ;
mp.Gender = true; using (System.IO.FileStream file = new System.IO.FileStream("myPerson.xml", System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
//创建自己写的序列化类对象
MyXmlSerializer myXmlSer = new MyXmlSerializer();
//调用序列化方法,保存到文件中。
myXmlSer.Serialize(file, mp);
}
MessageBox.Show("ok");
}
} public class MyPerson
{
private string name;
private int age;
private bool gender; [MyXmlIgnore] //添加特性,这个公有的属性将不被序列化,在序列化方法里实现。
public bool Gender
{
get { return gender; }
set { gender = value; }
} public int Age
{
get { return age; }
set { age = value; }
} public string Name
{
get { return name; }
set { name = value; }
} }
//模拟写一个序列化方法类
public class MyXmlSerializer
{
/// <summary>
/// 使用指定的 System.IO.Stream 序列化指定的 System.Object 并将 XML 文档写入文件。
/// </summary>
/// <param name="stream">用于编写 XML 文档的 System.IO.Stream。</param>
/// <param name="o">将要序列化的 System.Object。</param>
public void Serialize(System.IO.Stream stream, object o)
{
//通过反射获取对象类型
Type typeObj = o.GetType(); //创建XML文档
System.Xml.Linq.XDocument xdoc = new System.Xml.Linq.XDocument();
//创建XML元素,获取对象类型类名称作为,XML根节点名称
System.Xml.Linq.XElement xRoot = new System.Xml.Linq.XElement(typeObj.Name);
//添加到XML根节点
xdoc.Add(xRoot); //通过反射获取这个类型的所有公共属性
System.Reflection.PropertyInfo[] pinfos = typeObj.GetProperties(); //遍历pinfos每个属性都有创建XML元素
foreach (System.Reflection.PropertyInfo info in pinfos)
{
//通过每个属性获取它的特性,判断有没有MyXmlIgnoreAttribute特性,如果没有才给序列化。
object[] objAttrs = info.GetCustomAttributes(typeof(MyXmlIgnoreAttribute), false);
//当小于等于0时,可判定该属性没有MyXmlIgnoreAttribute特性,可以被序列化。
if (objAttrs.Length <= )
{
System.Xml.Linq.XElement xelet = new System.Xml.Linq.XElement(info.Name, info.GetValue(o));
xRoot.Add(xelet); //添加到根节点下面
}
//有MyXmlIgnoreAttribute特性的就不写入XML。
}
//保存XML到流中去
xdoc.Save(stream);
}
} //不序列化属性字段特性
public class MyXmlIgnoreAttribute : Attribute
{ }
}
关于反序列化:
<?xml version="1.0"?>
<PersonRoot>
<Person>
<Age>18</Age>
<Name>张三</Name>
</Person>
<Person>
<Age>19</Age>
<Name>李四</Name>
</Person>
</PersonRoot>
public class PersonRoot
{
List<Person> perList = new List<Person>(); [XmlElement(ElementName = "Person")]
public List<Person> PerList
{
get { return perList; }
set { perList = value; }
}
}
using (System.IO.FileStream file = File.OpenRead("personList.xml"))
{
XmlSerializer xmlSer = new XmlSerializer(typeof(PersonRoot));
PersonRoot list = (PersonRoot)xmlSer.Deserialize(file);
MessageBox.Show(list.PerList[].Name);
}
XML数据格式,
<ArrayOfPerson>
<Person>
可以直接List<Person>类型反序列化到List<Person>对象中。
Attribute:
Attribute 类将预定义的系统信息或用户定义的自定义信息与目标元素相关联。 目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、可移植可执行文件模块、参数、属性、返回值、结构或其他特性。
特性所提供的信息也称为元数据。 元数据可由应用程序在运行时进行检查以控制程序处理数据的方式,也可以由外部工具在运行前检查以控制应用程序处理或维护自身的方式。 例如,.NET Framework 预定义特性类型并使用特性类型控制运行时行为,某些编程语言使用特性类型表示 .NET Framework 常规类型系统不直接支持的语言功能。
所有特性类型都直接或间接地从 Attribute 类派生。 特性可应用于任何目标元素;多个特性可应用于同一目标元素;并且特性可由从目标元素派生的元素继承。 使用 AttributeTargets 类可以指定特性所应用到的目标元素。
Attribute 类提供检索和测试自定义特性的简便方法。 有关使用特性的更多信息,请参见 应用特性和 利用特性扩展元数据。
下面的代码示例演示 Attribute 的用法。
using System;
using System.Reflection; // An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal {
// Pets.
Dog = ,
Cat,
Bird,
} // A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute {
// The constructor is called when the attribute is set.
public AnimalTypeAttribute(Animal pet) {
thePet = pet;
} // Keep a variable internally ...
protected Animal thePet; // .. and show a copy to the outside world.
public Animal Pet {
get { return thePet; }
set { thePet = value; }
}
} // A test class where each method has its own pet.
class AnimalTypeTestClass {
[AnimalType(Animal.Dog)]
public void DogMethod() {} [AnimalType(Animal.Cat)]
public void CatMethod() {} [AnimalType(Animal.Bird)]
public void BirdMethod() {}
} class DemoClass {
static void Main(string[] args) {
AnimalTypeTestClass testClass = new AnimalTypeTestClass();
Type type = testClass.GetType();
// Iterate through all the methods of the class.
foreach(MethodInfo mInfo in type.GetMethods()) {
// Iterate through all the Attributes for each method.
foreach (Attribute attr in
Attribute.GetCustomAttributes(mInfo)) {
// Check for the AnimalType attribute.
if (attr.GetType() == typeof(AnimalTypeAttribute))
Console.WriteLine(
"Method {0} has a pet {1} attribute.",
mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
} }
}
}
/*
* Output:
* Method DogMethod has a pet Dog attribute.
* Method CatMethod has a pet Cat attribute.
* Method BirdMethod has a pet Bird attribute.
*/
C# 二进制序列化(BinaryFormatter),Xml序列化(XmlSerializer),自己模拟写一个Xml序列化过程。的更多相关文章
- 写一个xml文件到磁盘的方法
/** * 往磁盘上写一个xml文件 * * <?xml version="1.0" encoding="UTF-8" standalone=" ...
- 一个可序列化的C#对象,如何转成一个XML格式的文件或字符串【转】
原文:http://blog.csdn.net/otong/article/details/7894059 序列化或反序列化成一个字符串: 方法一: 序列化: public static string ...
- 把xml格式的字符串写入到一个xml文件中
package demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; impo ...
- 通常一个 Xml 映射文件,都会写一个 Dao 接口与之对应, 请问,这个 Dao 接口的工作原理是什么?Dao 接口里的方法, 参数不同时,方法能重载吗?
Dao 接口即 Mapper 接口.接口的全限名,就是映射文件中的 namespace 的值: 接口的方法名,就是映射文件中 Mapper 的 Statement 的 id 值:接口方法内的 参数,就 ...
- 通常一个Xml映射文件,都会写一个Dao接口与之对应,请问,这个Dao接口的工作原理是什么?Dao接口里的方法,参数不同时,方法能重载吗?
Dao接口即Mapper接口.接口的全限名,就是映射文件中的namespace的值:接口的方法名,就是映射文件中Mapper的Statement的id值:接口方法内的参数,就是传递给sql的参数. M ...
- testng入门教程16数据驱动(把数据写在xml)
testng入门教程16数据驱动(把数据写在xml) testng入门教程16数据驱动(把数据写在xml)把数据写在xml文件里面,在xml文件右键选择runas---testng执行 下面是case ...
- c# 序列化BinaryFormatter、SoapFormatter和XmlSerializer的区别
在C#中常见的序列化的方法主要也有三个:BinaryFormatter.SoapFormatter.XML序列化 1.BinaryFormatter 序列化 [Serializable] //如果要想 ...
- C#操作Xml:XmlSerializer 对象的Xml序列化和反序列化
这篇随笔对应的.Net命名空间是System.Xml.Serialization:文中的示例代码需要引用这个命名空间. 为什么要做序列化和反序列化? .Net程序执行时,对象都驻留在内存中:内存中的对 ...
- wcf中序列化BinaryFormatter,DataContractJsonSerializer,DataContractSerializer,SoapFormatter,XmlSerializer
using System; using System.Runtime.Serialization; using System.Xml.Serialization; namespace Larryle. ...
随机推荐
- Trees in a Wood. UVA 10214 欧拉函数或者容斥定理 给定a,b求 |x|<=a, |y|<=b这个范围内的所有整点不包括原点都种一棵树。求出你站在原点向四周看到的树的数量/总的树的数量的值。
/** 题目:Trees in a Wood. UVA 10214 链接:https://vjudge.net/problem/UVA-10214 题意:给定a,b求 |x|<=a, |y|&l ...
- UVa 12563 劲歌金曲 刘汝佳第二版例题9-5;
Problem J Jin Ge Jin Qu [h]ao (If you smiled when you see the title, this problem is for you ^_^) Fo ...
- PHP : ActiveRecord实现示例
先简单介绍一下Active Record: Active Record(中文名:活动记录)是一种领域模型模式,特点是一个模型类对应关系型数据库中的一个表,而模型类的一个实例对应表中的一行记录.Acti ...
- Error:指向绑定函数的指针只能用于调用函数
a1.determinant; 改为: a1.determinant(); Eigen::MatrixXd a1(,);//ImagePoint a1<<n1,p1,n2,p2; doub ...
- FTP(File Transfer Protocol)是什么?
文件传输协议 FTP(File Transfer Protocol),是文件传输协议的简称.用于Internet上的控制文件的双向传输.同时,它也是一个应用程序(Application).用户可以通过 ...
- 瀑布流 jquery。
本人小菜鸟一仅仅,为了自我学习和交流PHP(jquery,linux,lamp,shell,javascript,server)等一系列的知识,小菜鸟创建了一个群. 希望光临本博客的人能够进来交流. ...
- 1.SpringMvc--初识springmvc
引自@精品唯居 springMvc是什么 springmvc是表现层的框架,是一个spring的表现层组件.是整个spring框架的一部分,但是也可以不使用springmvc.跟struts2框架功能 ...
- IIPP迷你项目(三)“Stopwatch: The Game”
0 本周项目说明 这一次博客是Coursera的IIPP课程第三周迷你项目的实现,基础要求是做一个秒表,能start能stop能reset,更高的要求是在此秒表的基础上完成两个小游戏,但是鉴于第二个小 ...
- 关于angularjs的select下拉列表存在空白的解决办法
angularjs 的select的option是通过循环造成的,循环的方式可能有ng-option或者</option ng-repeat></option>option中 ...
- Linux下带宽流量工具iftop实践
在Linux/类Unix系统中可以使用top查看系统资源.进程.内存占用等信息.查看网络状态可以使用netstat.nmap等工具.若要查看实时的网络流量,监控TCP/IP连接等,则可以使用iftop ...