本文实例讲述了C#实现对象XML序列化的方法。分享给大家供大家参考。具体实现方法如下:
using system;
using system.xml;
using system.xml.serialization;
using system.text;
using system.io;
public class util
{
/// <summary>
/// 对象序列化成 xml string
/// </summary>
public static string xmlserialize<t>(t obj)
{
string xmlstring = string.empty;
xmlserializer xmlserializer = new xmlserializer(typeof(t));
using (memorystream ms = new memorystream())
{
xmlserializer.serialize(ms, obj);
xmlstring = encoding.utf8.getstring(ms.toarray());
}
return xmlstring;
}
/// <summary>
/// xml string 反序列化成对象
/// </summary>
public static t xmldeserialize<t>(string xmlstring)
{
t t = default(t);
xmlserializer xmlserializer = new xmlserializer(typeof(t));
using (stream xmlstream = new memorystream(encoding.utf8.getbytes(xmlstring)))
{
using (xmlreader xmlreader = xmlreader.create(xmlstream))
{
object obj = xmlserializer.deserialize(xmlreader);
t = (t)obj;
}
}
return t;
}
}
stringwriter,xmlserializer将对象、对象集合序列化为xml格式的字符串, 同时描述如何进行反序列化.
c# 序列化 xmlserializer,binaryformatter,soapformatter
//radio.cs
using system;
using system.collections.generic;
using system.text;
namespace simpleserialize
{
[serializable]
public class radio
{
public bool hastweeters;
public bool hassubwoofers;
public double[] stationpresets;
[nonserialized]
public string radioid = "xf-552rr6";
}
}
//cars.cs
using system;
using system.collections.generic;
using system.text;
using system.xml.serialization;
namespace simpleserialize
{
[serializable]
public class car
{
public radio theradio = new radio();
public bool ishatchback;
}
[serializable, xmlroot(namespace = "http://www.intertech.com")]
public class jamesbondcar : car
{
[xmlattribute]
public bool canfly;
[xmlattribute]
public bool cansubmerge;
public jamesbondcar(bool skyworthy, bool seaworthy)
{
canfly = skyworthy;
cansubmerge = seaworthy;
}
// the xmlserializer demands a default constructor!
public jamesbondcar() { }
}
}
//program.cs
using system;
using system.collections.generic;
using system.text;
using system.io;
// for the formatters.
using system.runtime.serialization.formatters.binary;
using system.runtime.serialization.formatters.soap;
using system.xml.serialization;
namespace simpleserialize
{
class program
{
static void main(string[] args)
{
console.writeline("***** fun with object serialization *****n");
// make a jamesbondcar and set state.
jamesbondcar jbc = new jamesbondcar();
jbc.canfly = true;
&nbH\^[\X
^X\[\KB\[Y\^XH]\[Y\NB[\YX]\[X]H][\YX]\
NB\X[HX[HH][\X[J[^X˙]B[[[KX]K[XX\]K[\\KJJOBB[X]X[^JX[K^XBOBK][[JIY\[[\HHNBOBYBOBO]Bn#9&)ny"y`9n+bx |