This week ,i research something about XmlSerializer. now ,i want to talk something about this subject.
in order to transfers data,usual we should do xml serialize and deserialize,so we should
microsoft visual studio2005 provide a class XmlSerializer to do xml serialize,frist of all ,we should know xml structure,include xmlroot ,xmlelement, xmlattribute and so on.
Example:in this expression
<DocumentElement>
<temp userid= "4">
<name>1111</name>
</userid>
<DocumentElement>
<DocumentElement> is the xmlroot ,and <name> is xmlelement ,</userid> is xmlattribute,so you should know this concept.
so when serialize the xml ,so we should get the object type which will be serialize. Example : XmlSerializer ser = new XmlSerializer(o.GetType());through this sentence we get a xmlserializer object ,
the second,we should create a xmltextwriter to editor xml data.if we want to create,we must create a memory stream use to store data stream which has been by xmltextwriter.
Example:
System.IO.MemoryStream mem = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
and the last step we can serialize the data stream,and close xmltextwriter.
Example:
ser.Serialize(writer, o, ns);
ok,now we have already complish xml serialize.
all code:
public static string myXmlSerializer(object o)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer ser = new XmlSerializer(o.GetType());
System.IO.MemoryStream mem = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8);
ser.Serialize(writer, o, ns);
writer.Close();
return Encoding.UTF8.GetString(mem.ToArray());
}
about Deserialize,like serialize ,we also should get the string and xml type.the two thing has been transfers as parament.
Code Example:
public static object myXmlDeserialize(string s, Type t)
{
XmlSerializer mySerializer = new XmlSerializer(t);
StreamReader mem2 = new StreamReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s)), System.Text.Encoding.UTF8);
return mySerializer.Deserialize(mem2);
}
i will write something about how to construct.