关于使用XmlSerializer 序列化和反序列化的问题?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于使用XmlSerializer 序列化和反序列化的问题?相关的知识,希望对你有一定的参考价值。
aspx页面上有MagnetPullStrength,MagnetGrade,VisibleCustomerID三个textbox控件,现在需要将这三个框内的值以XML序列化存入到product表内ExtensionData这一列内(原话the data must be serialized into XML and stored only in the one column named ExtensionData.),并且读取的时候也要用反序列化来读取。
可是在msdn上看了还是不太明白要怎么弄
http://msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlserializer.aspx
要求的存入数据库的格式大概是这样
<ExtensionData>
<MagnetPullStrength>123
</MagnetPullStrength>
<MagnetGrade>23
<MagnetGrade>
<VisibleCustomerID>12,22,21,34,54,58639
</VisibleCustomerID>
</ExtensionData>
求助各位大大帮忙指点下 最好有代码例子 谢谢了
必须要用到XmlSerializer这个类
public class Extensiondata
public string MagnetPullStrength;
public string MagnetGrade;
public string VisibleCustomerID;
XmlSerializer serializer = new XmlSerializer(typeof(Extensiondata));
TextWriter writer = new StreamWriter(CommonLogic.SafeMapPath("images\\po.xml"));
Extensiondata po = new Extensiondata();
po.MagnetPullStrength = TextBox1.Text;
po.MagnetGrade = TextBox2.Text;
po.VisibleCustomerID = TextBox3.Text;
serializer.Serialize(writer, po);
writer.Close(); 参考技术A 建一个类
[XmlRoot("ExtensionData")]
class ExtensionData
[XmlElement("MagnetPullStrength")]
public int MagnetPullStrength get; set;
[XmlElement("MagnetGrade")]
public int MagnetGrade get; set;
[XmlElement("VisibleCustomerID")]
public string VisibleCustomerID get; set;
C# XML序列化和反序列化(XmlSerializer)
概述
XML序列化和反序列化是C#的常用技术,实现的方式有很多种,序列化即将对象转化为便于传输的数据格式, 常见的方法有:二进制,字节数组,json字符串,xml字符串等。今天主要通过XmlSerializer类的Serialize和Deserialize方法实现.
标注
如果使用XmlSerializer类实现序列化,不需要用[Serializable]属性标记对象的类型。如果用DataContractSerializer序列化对象,则需要标注[Serializable]或[DataContract]。
需要序列化的类型前标注 [XmlRoot("Name")],表示根节点;
[XmlType(TypeName = "Name")] 节点
[XmlElement("Name")] 元素
[XmlAttribute("Name")] 属性
[XmlArray] 声明集合
详见:微软官网:https://learn.microsoft.com/zh-cn/dotnet/standard/serialization/attributes-that-control-xml-serialization
Mark:
1. 私有属性不会被序列化;
2. 标注为[XmlIgnore]的共有属性也不会被序列化;
3. 枚举类型的属性序列化之前需要赋值
实例
using Caliburn.Micro.Hello.Helper;
using Caliburn.Micro.Hello.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Caliburn.Micro.Hello.ViewModels
public class XmlSerializerViewModel : Screen, IViewModel
private StringBuilder stringBuilder = new StringBuilder();
public string DisplayInfo get; set;
public XmlSerializerViewModel()
DisplayName = "XmlSerializer";
xmlFile();
SerializeToXml();
DeserializeXml();
DisplayInfo = stringBuilder.ToString();
public void xmlFile()
XmlFile xmlFile = new XmlFile();
xmlFile.CreateXmlFile("ReviewParams", "maxValue", "30");
public void SerializeToXml()
//测试序列化
var xml = "";
StudentList de = new StudentList();
var person1 = new Student();
person1.Name = "郭德纲";
person1.Age = 58;
person1.Sex = "男";
var person2 = new Student();
person2.Name = "洪金宝";
person2.Age = 72;
person2.Sex = "男";
de.data = new List<Student>();
de.data.Add(person1);
de.data.Add(person2);
xml = XmlHelper.serialize(de);
stringBuilder.AppendLine(xml);
//XmlHelper.SerializeToXml(de);
XmlHelper.SerializeToXml(new DocumentDic());
public void DeserializeXml()
var content = File.ReadAllText(Environment.CurrentDirectory + @"\\myxml.xml");
DocumentDic dee = XmlHelper.deserialize(content, typeof(DocumentDic)) as DocumentDic;
if (dee != null)
foreach (var item in dee.dataDic.Values)
stringBuilder.AppendLine(item.Name);
运行结果:
这里要注意的是 xtw.Formatting = Formatting.Indented;//可实现换行显示;Dictionary本身不支持序列化,所以需要重写为可序列化的SerializableDictionary;
SerializeToXml:
public static void SerializeToXml(object o)
var type = o.GetType();
if (o == null)
return;
//序列化对象
XmlSerializer serializer = new XmlSerializer(type);
using (XmlTextWriter xtw = new XmlTextWriter("myxml.xml", Encoding.UTF8)) //用XmlTextWriter 创建一个XML文件
xtw.Formatting = Formatting.Indented;//可实现换行显示
serializer.Serialize(xtw, o);
;
反序化xml为对象:
/// <summary>
/// 反序化xml为对象
/// </summary>
/// <param name="xml"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object deserialize(string xml, Type type)
try
using (StringReader sr = new StringReader(xml))
XmlSerializer serializer = new XmlSerializer(type);
return serializer.Deserialize(sr);
catch (Exception e)
return null;
数据模型:
//对象定义
[XmlRoot("RecipeData")]
//[DataContract(Name = "RecipeData", Namespace = "DataContracts")]
[Serializable]
public class DocumentDic
public DocumentDic()
dataDic = new SerializableDictionary<string, Student>();
var person = new Student();
person.Name = "韦小宝";
person.Age = 65;
person.Sex = "男";
dataDic.Add("明星", person);
[XmlElement("DataTable")] //DataTable平行出现,不出现data
//[XmlIgnore]
//[DataMember(Name = "dataDic")]
public SerializableDictionary<string, Student> dataDic get; set;
//对象定义
[XmlRoot("StudentList")]
public class StudentList
//[XmlArray("Students"), XmlArrayItem("Student")]
[XmlElement("Students")]
public List<Student> data get; set;
[XmlRoot("Student")]
public class Student
[XmlElement("Name")]
public string Name get; set;
[XmlElement("Age")]
public int Age get; set;
[XmlElement("Sex")]
public string Sex get; set;
此外还可以用DataContractSerializer,
DataContractSerializer 与 XMLSerializer的区别:
① 需要序列化对象的所有公共和私有字段和属性,可以使用 DataContractSerializer 而不要使用 XML 序列化。
②DataContractSerializer 的性能优于 Xmlserializer。DataContractSerializer 序列化所有标记为 [DataMember] 属性的成员,即使成员标记为私有。一个类不同时使用[Serializable]和[DataContract]标签。
源码下载
链接:https://pan.baidu.com/s/1y1PqmsmHj-roDWv9Pou0LQ
提取码:6666
本文参考:如有侵权,请联系小编删除!
1. 【C# XML 序列化】开篇 - https://www.cnblogs.com/cdaniu/p/16093919.html
2. .NET中XML序列化和反序列化常用类和用来控制XML序列化的属性总结 - https://zhuanlan.zhihu.com/p/487914400
以上是关于关于使用XmlSerializer 序列化和反序列化的问题?的主要内容,如果未能解决你的问题,请参考以下文章
XmlSerializer c++ 使用多个命名空间反序列化
XmlSerializer(Type type, Type[] extraTypes) 内存泄漏