XML入门二
【摘要】 Xml基础02
Xml基础02
几种序列化方式和反序列化:
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;
namespace day29test03
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//声明对象方式
Person person = new Person();
person.Age = 20;
person.Name = "qew";
person.Height = 1777;
//序列方式 基本的xml序列化
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
System.IO.TextWriter yw = new System.IO.StreamWriter(@"F:\.net学习\test\xmldeemp1\1.xml");
xmlSerializer.Serialize(yw, person);
yw.Dispose();
//二进制序列化 通用性强
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
//soap序列化 用于网络上传输数据
//SoapSeriailzation
//输出序列化后的流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
xmlSerializer.Serialize(ms, person);
//缓冲过的
byte[] ns = ms.GetBuffer();
String str = System.Text.Encoding.UTF8.GetString(ns);
MessageBox.Show(str);
//没经过缓冲的
//byte[] vs = ms.ToArray();
}
private void button2_Click(object sender, EventArgs e)
{
//反序列化
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
System.IO.TextReader tr = new System.IO.StreamReader(@"F:\.net学习\test\xmldeemp1\1.xml");
Person p = (Person)xmlSerializer.Deserialize(tr);
//xmlSerializer.Deserialize();
}
}
[System.Xml.Serialization.XmlRoot("mtxml", Namespace="www.nb.com")]
public class Person
{
private String name;
private int age;
private double height;
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public double Height { get => height; set => height = value; }
}
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)