Xml serial object and reverse string row instance

Source: Internet
Author: User

A simple example, but it is very practical. Directly serialize an object into an xml file, and use a line string as an object.
Method:

1 using System;
2 using System. Collections. Generic;
3 using System. Text;
4 using System. IO;
5 using System. Xml;
6 using System. Xml. Serialization;
7 using System. Collections. ObjectModel;
8
9 namespace XmlBuilder
10 {
11/*** // <summary>
12 ///
13 /// </summary>
14 public static class Localization
15 {
16 public method # region Public Method
17/** // <summary>
18 // serialize the object
19 /// </summary>
20 /// <param name = "filename"> File Information name </param>
21 /// <param name = "obj"> object to be serialized </param>
22 public static void SerializeObject (string fileName, object obj)
23 {
24 Stream writer = null;
25 try
26 {
27 Type type = obj. GetType ();
28 XmlSerializer serializer = new XmlSerializer (type );
29
30 writer = new FileStream (fileName, FileMode. Create );
31 serializer. Serialize (writer, obj );
32}
33 catch (Exception ex)
34 {
35 throw ex;
36}
37 finally
38 {
39 if (writer! = Null)
40 writer. Close ();
41}
42}
43
44/*** // <summary>
45 // deserialization object
46 /// </summary>
47 // <param name = "fileNmae"> File Information name </param>
48 /// <param name = "type"> deserialization object type </param>
49 // <returns> return the object after instantiation </returns>
50 public static object DeSerializeObject (string fileName, Type type)
51 {
52 if (! File. Exists (fileName ))
53 return null;
54
55 FileStream fs = null;
56 try
57 {
58 fs = new FileStream (fileName, FileMode. Open );
59
60 XmlSerializer xSer = new XmlSerializer (type );
61 XmlReader reader = new XmlTextReader (fs );
62 return xSer. Deserialize (reader );
63}
64 catch (Exception ex)
65 {
66 throw ex;
67}
68 finally
69 {
70 if (fs! = Null)
71 {
72 fs. Close ();
73}
74}
75}
76 # endregion
77}
78}
79

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.