XMLSerialisierung ist der Prozess der Konvertierung der öffentlichen Eigenschaften und Felder eines Objekts in das XML-Format zur Speicherung oder Übertragung. Durch die Deserialisierung wird der ursprüngliche Zustand des Objekts aus der XML-Ausgabe wiederhergestellt. Die wichtigste Klasse bei der XML-Serialisierung ist die XmlSerializer-Klasse. Seine wichtigsten Methoden sind die Methoden Serialize und Deserialize, die sich im Namespace System.Xml.Serialization befinden.
namespace 学习测试 { class Program { static void Main(string[] args) { Person p = new Person(1, "刘备", 176); string xmlString = ""; //xml序列化开始 using (MemoryStream ms = new MemoryStream()) { Type t = p.GetType(); XmlSerializer xml = new XmlSerializer(t); xml.Serialize(ms, p); byte[] arr = ms.ToArray(); xmlString = Encoding.UTF8.GetString(arr, 0, arr.Length); ms.Close(); } Console.WriteLine(xmlString); Console.ReadKey(); } } public class Person { //必须定义一个无参数构造函数,否则无法序列化(当然完全不写构造函数也是可以序列化的,因为有个默认的无参构造函数) public Person() { } public Person(int id, string name, int age) { Id = id; Name = name; //Age = age; } public int Id { get; set; } public string Name { get; set; } //私有字段 private int Age { get; set; } //只读属性 private int height; public int Height { get { return height; } } } }
Weitere Notizen:
Indizes
, Private Felder oder schreibgeschützte Eigenschaften (außer schreibgeschützte Sammlungseigenschaften) können nicht serialisiert werden.Klassen, die serialisiert werden müssen, müssen eine parameterlose Konstruktorfunktion haben
IDictionary (wie HashTable)
Schnittstelle
)Wenn Sie dies nicht tun Wenn Sie ein Attribut serialisieren möchten, verwenden Sie das Tag [System.Xml.Serialization.XmlIgnore], das für Attribute verwendet werden kann.
Strukturen
usw.2. Ändern Sie den Standardwert der XML-Serialisierung
Normalerweise werden im Prozess der XML-Serialisierung viele Dinge automatisch generiert, z XML-Namespace, Codierung usw.Ausgabevergleich:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); //第一个参数是前缀,第二个参数是命名空间 //然后在序列化的时候,指定自定义命名空间 xml.Serialize(ms, p, ns);
2. Entfernen Sie die XML-Deklaration: > Ausgabe:
3、换行缩进 当XmlWriterSettings如此设置后,输出的XML为: 4、指定缩进字符 输出如下: XmlWriterSettings更多设置属性如下: http://msdn.microsoft.com/zh-cn/library/system.xml.xmlwritersettings(v=vs.110).aspx 实现IXmlSerializable接口之后,我们能够自定义类序列化的方式。 该接口包含3个方法: 简单示例: 输出如下: 我们都知道,接口是不支持序列化的。下面来做个有用的示例,实现IList 输出如下: 以上代码是能够直接用于序列化数组的,也就是IList 下面给出一个序列化与反序列化通过反射的复杂对象的示例: 以上代码输出: 特别提示,一定要特别特别注意,ReadStartElement与ReadEndElement的问题,否则很容易出现反序列化集合时只能够读取第一个的情况。而对于序列化,如果WriteStartElement与WriteEndElement不匹配,出现的只是XML标签对不匹配的问题,没Read的时候那么坑。 有时,我们在序列化时想要自定义XML的结构,这时候就要用到我们的属性类了。属性类提供了很多特性供我们使用,以完成自定义序列化功能。 下面仅仅给出两个简单示例: 2013/12/27 常遇错误记录: 反序列化错误提示: 1、XML 文档(2, 2)中有错误: 报这个错误一般是由于序列化与反序列化的类型不一致: 2014/08/12 2、XmlIgnore与NonSerialized的区别。 1、XmlIgnore能作用于属性,NonSerialized只作用于字段。 2、XmlIgnore对序列化与反序列化均有效,而NonSerialized只影响序列化,反序列化不管。(非百分百确定) Das obige ist der detaillierte Inhalt vonDetaillierte Erläuterung des grafischen Codes der XML-Serialisierung. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website! settings.Indent = true;
settings.IndentChars = "--";
成员 说明 CloseOutput 获取或设置一个值,该值指示在调用 Close 方法时,XmlWriter 是否还应该关闭基础流或 TextWriter。 Encoding 获取或设置要使用的文本编码的类型。 Indent 获取或设置一个值,该值指示是否缩进元素。 IndentChars 获取或设置缩进时要使用的字符串。 NamespaceHandling 获取或设置一个值,该值指示在编写 XML 内容时,XmlWriter 是否应移除重复的命名空间声明。 的默认是输出程序中出现的所有命名空间声明。 NewLineChars 获取或设置要用于分行符的字符串 NewLineHandling 获取或设置一个值,该值指示是否将输出中的分行符正常化。 NewLineOnAttributes 获取或设置一个值,该值指示是否将属性写入新行。 OmitXmlDeclaration 获取或设置一个值指示省略 XML 声明。 Encoding 获取或设置要使用的文本编码的类型。 Reset方法 重置以上属性 三、实现序列化接口IXmlSerializable
XmlSchema GetSchema();
void ReadXml(XmlReader reader);
void WriteXml(XmlWriter writer);
namespace 自定义序列化
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Id = 1;
p.Name = "刘备";
string str = ObjectToXmlSerializer(p);
Console.WriteLine(str);
Person p1 = ObjectToXmlDESerializer<Person>(str);
Console.WriteLine("我的名字是:" + p1.Name);
Console.ReadKey();
}
//序列化Xml
public static string ObjectToXmlSerializer(Object Obj)
{
string XmlString = "";
XmlWriterSettings settings = new XmlWriterSettings();
//去除xml声明
//settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.Encoding = Encoding.Default;
using (System.IO.MemoryStream mem = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(mem, settings))
{
//去除默认命名空间xmlns:xsd和xmlns:xsi
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer formatter = new XmlSerializer(Obj.GetType());
formatter.Serialize(writer, Obj, ns);
}
XmlString = Encoding.Default.GetString(mem.ToArray());
}
return XmlString;
}
//反序列化
public static T ObjectToXmlDESerializer<T>(string str)where T : class
{
object obj;
using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str)))
{
using (XmlReader reader = XmlReader.Create(mem))
{
XmlSerializer formatter = new XmlSerializer(typeof(T));
obj = formatter.Deserialize(reader);
}
}
return obj as T;
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class PersonSerializer : IXmlSerializable
{
private Person p;
public int Id { get; set; }
public string Name { get; set; }
#region IXmlSerializable 成员
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new NotImplementedException();
}
//如果这个方法默认则报:XML 文档(2, 2)中有错误。
void IXmlSerializable.ReadXml(XmlReader reader)
{
reader.ReadElementString("Person");
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteElementString("Id", Id.ToString());
writer.WriteElementString("Name", Name);
}
#endregion
}
}
namespace IList<T>的序列化与反序列化
{
class Program
{
static void Main(string[] args)
{
Woman w1 = new Woman() { Id = 1, Name = "貂蝉" };
Woman w2 = new Woman() { Id = 2, Name = "西施" };
List<Woman> ListWoman = new List<Woman>();
ListWoman.Add(w1);
ListWoman.Add(w2);
Person p = new Person();
p.Id = 1;
p.Name = "刘备";
p.ListWoman = ListWoman;
string str = ObjectToXmlSerializer(p);
Console.WriteLine(str);
Person p1 = ObjectToXmlDESerializer<Person>(str);
Console.WriteLine("我的名字是:" + p1.Name + "我的老婆有:");
foreach (Woman w in p1.ListWoman)
{
Console.WriteLine(w.Name);
}
Console.ReadKey();
}
//序列化Xml
public static string ObjectToXmlSerializer(Object Obj)
{
string XmlString = "";
XmlWriterSettings settings = new XmlWriterSettings();
//去除xml声明
//settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.Encoding = Encoding.Default;
using (System.IO.MemoryStream mem = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(mem, settings))
{
//去除默认命名空间xmlns:xsd和xmlns:xsi
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer formatter = new XmlSerializer(Obj.GetType());
formatter.Serialize(writer, Obj, ns);
}
XmlString = Encoding.Default.GetString(mem.ToArray());
}
return XmlString;
}
//反序列化
public static T ObjectToXmlDESerializer<T>(string str) where T : class
{
object obj;
using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str)))
{
using (XmlReader reader = XmlReader.Create(mem))
{
XmlSerializer formatter = new XmlSerializer(typeof(T));
obj = formatter.Deserialize(reader);
}
}
return obj as T;
}
}
public class Person : IXmlSerializable
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Woman> ListWoman { get; set; }
#region IXmlSerializable 成员
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new NotImplementedException();
}
void IXmlSerializable.ReadXml(XmlReader reader)
{
//一定要特别注意配对问题,否则很容易反序列化集合出现只能够读取第一个的情况
reader.ReadStartElement("Person");
Id = Convert.ToInt32(reader.ReadElementString("Id"));
Name = reader.ReadElementString("Name");
//我也不知道为什么,复杂类型只能够另外定义一个,获得值之后再给原来的赋值
List<Woman> ListWoman2 = new List<Woman>();
reader.ReadStartElement("ListWoman");
while (reader.IsStartElement("Woman"))
{
Woman w = new Woman();
reader.ReadStartElement("Woman");
w.Id = Convert.ToInt32(reader.ReadElementString("Id"));
w.Name = reader.ReadElementString("Name");
reader.ReadEndElement();
reader.MoveToContent();
ListWoman2.Add(w);
}
ListWoman = ListWoman2;
reader.ReadEndElement();
reader.ReadEndElement();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
//这里是不需要WriteStart/End Person的
writer.WriteElementString("Id", Id.ToString());
writer.WriteElementString("Name", Name);
//有重载,想设置命名空间,只需在参数加上
writer.WriteStartElement("ListWoman");
foreach (Woman item in ListWoman)
{
PropertyInfo[] ProArr = item.GetType().GetProperties();
writer.WriteStartElement("Woman");
foreach (PropertyInfo p in ProArr)
{
writer.WriteElementString(p.Name, p.GetValue(item, null).ToString());
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
#endregion
}
public class Woman
{
public int Id { get; set; }
public string Name { get; set; }
}
}
//序列化Xml
public static string ListToXmlSerializer<T>(IList<T> ListT)
{
XmlSerializer ser = new XmlSerializer(ListT.GetType());
System.IO.MemoryStream mem = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = false;
settings.Encoding = Encoding.UTF8;
XmlWriter writer = XmlWriter.Create(mem, settings);
ser.Serialize(writer, ListT);
writer.Close();
string strtmp = Encoding.UTF8.GetString(mem.ToArray());
return strtmp;
}
//反序列化Xml
public static List<T> XmlToListSerializer<T>(Stream stream)
{
string XmlPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\OutLine\" + typeof(T).Name + ".xml";
using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>));
var listsch = ser.Deserialize(sr);
List<T> reses = listsch as List<T>;
return reses;
}
}
using System.Linq.Expressions;namespace 控制台___学习测试
{
class Program
{
static void Main(string[] args)
{
Woman w1 = new Woman() { Id = 1, Name = "貂蝉" };
Woman w2 = new Woman() { Id = 2, Name = "西施" };
List<Woman> ListWoman1 = new List<Woman>();
ListWoman1.Add(w1);
ListWoman1.Add(w2);
List<Person> ListPerson = new List<Person>();
Person p1 = new Person() { Id = 1, Name = "刘备", ListWoman = ListWoman1 };
Person p2 = new Person() { Id = 2, Name = "关羽", ListWoman = ListWoman1 };
Person p3 = new Person() { Id = 3, Name = "张飞", ListWoman = ListWoman1 };
ListPerson.Add(p1);
ListPerson.Add(p2);
ListPerson.Add(p3);
string xml = ListToXmlSerializer(ListPerson);
Console.WriteLine(xml);
MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(xml));
List<Person> ListPerson2 = XmlToListSerializer<Person>(mem);
Console.WriteLine(ListPerson2.Count);
Console.WriteLine(ListPerson2[2].ListWoman[1].Name);
Console.ReadKey();
}
//序列化Xml
public static string ListToXmlSerializer<T>(IList<T> ListT)
{
XmlSerializer ser = new XmlSerializer(ListT.GetType());
System.IO.MemoryStream mem = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.Encoding = Encoding.UTF8;
XmlWriter writer = XmlWriter.Create(mem, settings);
ser.Serialize(writer, ListT);
writer.Close();
string strtmp = Encoding.UTF8.GetString(mem.ToArray());
File.WriteAllText(@"D:\222.xml", strtmp);
return strtmp;
}
//反序列化Xml
public static List<T> XmlToListSerializer<T>(Stream stream)
{
using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>));
var listsch = ser.Deserialize(sr);
List<T> reses = listsch as List<T>;
return reses;
}
}
}
public class Person : IXmlSerializable
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Woman> ListWoman { get; set; }
#region IXmlSerializable 成员
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new NotImplementedException();
}
void IXmlSerializable.ReadXml(XmlReader reader)
{
//while (reader.Name == "Person")
//{
reader.ReadStartElement("Person");
Id = Convert.ToInt32(reader.ReadElementString("Id"));
Name = reader.ReadElementString("Name");
List<Woman> newWomans = new List<Woman>();
PropertyInfo[] ProArr = typeof(Woman).GetProperties();
reader.ReadStartElement("ListWoman");
while (reader.IsStartElement("Woman"))
{
Woman Item2 = new Woman();
reader.ReadStartElement("Woman");
foreach (PropertyInfo p in ProArr)
{
string str = reader.ReadElementString(p.Name);
p.SetValue(Item2, Convert.ChangeType(str, p.PropertyType), null);
}
reader.ReadEndElement();
reader.MoveToContent();
newWomans.Add(Item2);
}
ListWoman = newWomans;
reader.ReadEndElement();
reader.ReadEndElement();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteElementString("Id", Id.ToString());
writer.WriteElementString("Name", Name);
writer.WriteStartElement("ListWoman");
foreach (Woman item in ListWoman)
{
PropertyInfo[] ProArr = item.GetType().GetProperties();
writer.WriteStartElement("Woman");
foreach (PropertyInfo p in ProArr)
{
if (p.GetValue(item, null) != null)
{
writer.WriteElementString(p.Name, p.GetValue(item, null).ToString());
}
else
{
writer.WriteElementString(p.Name, "");
}
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
#endregion
}
public class Woman
{
public int Id { get; set; }
public string Name { get; set; }
}
}
四、XML特性
名称 描述 XmlAttribute 表示一个特性对象的集合,这些对象控制XmlSerializer如何序列化和反序列化对象 XmlArrayAttribute 指定XmlSerializer应将特定的类成员序列化为XML元素数组 XmlArrayItemAttribute 指定XmlSerializer可以放置在序列化数组中的派生类型 XmlArrayItemAttributes 表示XmlArrayItemAttribute对象的集合 XmlAttributeAttribute 指定XmlSerializer应将类成员作为XML特性序列化 XmlChoiceIdentifierAttribute 指定可以通过使用枚举来进一步消除成员的歧义 XmlElementAttribute 在XmlSerializer序列化或反序列化包含对象时,指示公共字段或属性表示XML元素 XmlElementAttributes 表示XmlElementAttribute的集合,XmlSerializer将其用于它重写序列化类的默认方式 XmlEnumAttribute 控制XmlSerializer如何序列化枚举成员 XmlIgnoreAttribute 指示XmlSerializer方法不序列化公共字段或公共读/写属性值 XmlIncludeAttribute 允许XmlSerializer在它序列化或反序列化对象时识别类型 XmlRootAttribute 控制视为XML根元素的属性目标的XML序列化 XmlTextAttribute 当序列化或反序列化时,想XmlSerializer指示应将此成员作为XML文本处理 XmlTypeAttribute 控制当属性目标由XmlSerializer序列化时生成的XML结构 XmlAnyAttributeAttribute 指定成员(返回XmlAttribute对象的数组的字段)可以包含XML属性 XmlAnyElementAttribute 指定成员可以包含对象,该对象表示在序列化或反序列化的对象中没有相应成员的所有XML元素 XmlAnyElementAttributes 表示XmlAnyElementAttribute对象的集合 XmlAttributeEventArgs 为UnKnowAttribute提供数据 XmlAttributeOverrides 允许你在使用XmlSerializer序列化或反序列化时重写属性、字段和类特性 XmlElementEventArgs 为UnknownElement事件提供数据 XmlNamespaceDeclarationsAttribute 指定目标属性、参数、返回值或类成员包含与XML文档中所用命名空间关联的前缀 XmlNodeEventArgs 为UnknownNode时间提供数据 XmlSerializer 将对象序列化到XML文档中和从XML文档中反序列化对象,XmlSerializer使你得以控制如何将对象编码到XML中 XmlSerializerNamespaces 包含XmlSerializer用于在XML文档实例中生成限定名的XML命名空间和前缀 XmlTypeMapping 包含从一种类型到另一种类型的映射 namespace 学习测试
{
[Serializable]
public class Person
{
public Person() { }
public int Id { get; set; }
public string Name { get; set; }
[XmlAttribute(DataType = "string")]
public string Content { get; set; }
[XmlIgnore]
public int Age { get; set; }
[XmlArray]
[XmlArrayItem("Int32", typeof(Int32))]
public IList ListInt { get; set; }
}
class Program
{
static void Main(string[] args)
{
IList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
Person p = new Person();
p.Id = 1;
p.Name = "刘备";
p.Age = 23;
p.Content = "这是一个牛人";
p.ListInt = list;
string strXml = ObjectToXmlSerializer(p);
Console.WriteLine(strXml);
//反序列化IList还有问题
//Person p2 = ObjectToXmlDESerializer<Person>(strXml);
//Console.WriteLine(p2.Name);
Console.ReadKey();
}
//序列化
public static string ObjectToXmlSerializer(Object Obj)
{
string XmlString = "";
XmlWriterSettings settings = new XmlWriterSettings();
//去除xml声明
//settings.OmitXmlDeclaration = true;
settings.Indent = true;
settings.Encoding = Encoding.Default;
using (System.IO.MemoryStream mem = new MemoryStream())
{
using (XmlWriter writer = XmlWriter.Create(mem, settings))
{
//去除默认命名空间xmlns:xsd和xmlns:xsi
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer formatter = new XmlSerializer(Obj.GetType());
formatter.Serialize(writer, Obj, ns);
}
XmlString = Encoding.Default.GetString(mem.ToArray());
}
return XmlString;
}
//反序列化Xml
public static T ObjectToXmlDESerializer<T>(string str) where T : class
{
object obj;
using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str)))
{
using (XmlReader reader = XmlReader.Create(mem))
{
XmlSerializer formatter = new XmlSerializer(typeof(T));
obj = formatter.Deserialize(reader);
}
}
return obj as T;
}
}
}
XmlSerialize.Serialize(@"C:\Person.xml",person);
//person 是 Person类的对象var test = XmlSerialize.DeSerialize(typeof(Person), @"C:\Person.xml");