something about XmlSerializer

 

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值