Implement XML serialization and deserialization through XmlSerializer
Through XmlSerializer, we can easily convert the Model and XML.
GuanwenHere
Help
1 using System; 2 using System. text; 3 using System. xml. serialization; 4 using System. IO; 5 using System. xml; 6 7 namespace BLL 8 {9 public class XmlHelper 10 {11 public static T DeSerializeModels <T> (string XMLStr, string eleName) 12 {13 XmlRootAttribute Root = new XmlRootAttribute (); 14 Root. elementName = eleName; 15 16 XmlSerializer xs = new XmlSerializer (typeof (T), Root); 17 18 StringReader s TrReader = new StringReader (XMLStr); 19 System. xml. xmlReader r = new System. xml. xmlTextReader (strReader); 20 try 21 {22 T Result = (T) xs. deserialize (r); 23 return Result; 24} 25 finally 26 {27 strReader. close (); 28 r. close (); 29} 30} 31 32 public static string SerializeModels <T> (T Models, string eleName) 33 {34 StringBuilder sb = new StringBuilder (); 35 StringWriter w = new StringWriter (sb ); 36 37 XmlRootAttribute Root = new XmlRootAttribute (); 38 Root. elementName = eleName; 39 40 XmlSerializer sr = new XmlSerializer (typeof (T), Root); 41 sr. serialize (w, Models); 42 43 w. close (); 44 45 return sb. toString (); 46} 47 48 private static void XmlSerializeInternal (Stream stream, object o, Encoding encoding) 49 {50 if (o = null) 51 throw new ArgumentNullException ("o"); 52 if (encoding = nu Ll) 53 throw new ArgumentNullException ("encoding"); 54 55 XmlSerializer serializer = new XmlSerializer (o. getType (); 56 57 XmlWriterSettings settings = new XmlWriterSettings (); 58 settings. indent = true; 59 settings. newLineChars = "\ r \ n"; 60 settings. encoding = encoding; 61 settings. indentChars = ""; 62 63 using (XmlWriter writer = XmlWriter. create (stream, settings) 64 {65 serializer. serialize (Writer, o); 66 writer. close (); 67} 68} 69 70 // <summary> 71 // serialize an object to an XML string 72 /// </summary> 73 // <param name =" o "> target object </param> 74 // <param name =" encoding "> encoding method </param> 75 // XML generated by serialization <returns> string </returns> 76 public static string XmlSerialize (object o, encoding encoding) 77 {78 using (MemoryStream stream = new MemoryStream () 79 {80 XmlSerializeInternal (stream, o, encoding); 81 82 stream. position = 0; 83 using (StreamReader reader = new StreamReader (stream, encoding) 84 {85 return reader. readToEnd (); 86} 87} 88} 89 90 // <summary> 91 // serialize an object to an XML string 92 /// </summary> 93 // <param name = "o"> object to be serialized </param> 94 // <returns> serialized XML string </returns> 95 public static string XmlSerialize (object o) 96 {97 return XmlSerialize (o, Encoding. UTF8); 98} 99 100 // <summary> 101 // write an object serialized in XML to the object 102 // </summary> 103 // <param name = "o"> the object to be serialized </param> 104 // <param name = "UploadPath"> Save the file path </param> 105 // <param name = "encoding"> encoding method </param> 106 public static void XmlSerializeToFile (object o, string path, Encoding encoding) 107 {108 if (string. isNullOrEmpty (path) 109 throw new ArgumentNullException ("path"); 110 111 using (FileStream file = new FileStream (path, Fi LeMode. create, FileAccess. write) 112 {113 XmlSerializeInternal (file, o, encoding ); 114} 115} 116 117 // <summary> 118 // write an object to a file serialized in XML 119 // </summary> 120 /// <param name = "o"> object to be serialized </param> 121 // <param name = "UploadPath"> Save file path </param> 122 public static void XmlSerializeToFile (object o, string path) 123 {124 XmlSerializeToFile (o, path, Encoding. UTF8); 125} 126 127 // <summary> 128 // from XM L deserialization object 129 // </summary> 130 // <typeparam name = "T"> result object type </typeparam> 131 // <param name = "s"> XML string containing the object </param> 132 // <param name = "encoding"> encoding method </param> 133 // <returns> serialized object </returns> 134 public static T XmlDeserialize <T> (string s, encoding encoding) 135 {136 if (string. isNullOrEmpty (s) 137 throw new ArgumentNullException ("s"); 138 if (encoding = null) 139 throw new ArgumentNullExceptio N ("encoding"); 140 141 XmlSerializer xs = new XmlSerializer (typeof (T); 142 using (MemoryStream MS = new MemoryStream (encoding. getBytes (s) 143 {144 using (StreamReader sr = new StreamReader (MS, encoding) 145 {146 return (T) xs. deserialize (sr ); 147} 148} 149} 150 151 // <summary> 152 // deserialize object 153 from an XML string /// </summary> 154 // <typeparam name = "T"> result object type </typeparam> 155 // <param name = "s"> contains the XML string of the object </ Param> 156 // <returns> deserialized object </returns> 157 public static T XmlDeserialize <T> (string s) 158 {159 return XmlDeserialize <T> (s, Encoding. UTF8); 160} 161 162 // <summary> 163 // read a file and deserialize the object in XML format. 164 /// </summary> 165 // <typeparam name = "T"> result object type </typeparam> 166 // <param name = "UploadPath"> File path </param> 167 // <param name = "encoding"> encoding method </param> 168 // <returns> deserialized object </returns> 169 public static T XmlDeserializeFromFile <T> (string path, encoding encoding) 170 {171 if (string. isNullOrEmpty (path) 172 throw new ArgumentNullException ("path"); 173 if (encoding = null) 174 throw new ArgumentNullE Xception ("encoding"); 175 176 string xml = File. readAllText (path, encoding); 177 return XmlDeserialize <T> (xml, encoding); 178} 179 180 // <summary> 181 // read a file, and deserialize the object in XML format. 182 /// </summary> 183 // <typeparam name = "T"> result object type </typeparam> 184 // <param name = "UploadPath"> File path </param> 185 // <returns> deserialized object </returns> 186 public static T XmlDeserializeFromFile <T> (string path) 187 {188 return XmlDeserializeFromFile <T> (path, Encoding. UTF8); 189} 190} 191}Tool
You can also set the Model feature to flexibly control serialization.
Using System. xml. serialization; using System. collections. generic; namespace Model {// <summary> // The node name is EleTeacher /// </summary> [Serializable] [XmlType ("EleTeacher")] public class Teacher {[XmlElement (ElementName = "user")] public string AuthorID {set; get;} [XmlIgnore] public string Content {set; get ;} [XmlText] public string Value {set; get;} [XmlArray ("students")] public List <Student> sds {set; get ;}} [Serializable] public class Student {[XmlAttribute (AttributeName = "id")] public string ID {set; get ;}[ XmlText] public string Name {set; get ;}}}Model
XmlSerializerDeserialize () for Xml deserialization ()
Send me the serialization and deserialization methods. You can replace the double quotation marks below the serialization:
# Region XML-related static methods
/// <Summary>
/// Use XmlSerializer to serialize an object
/// </Summary>
/// <Typeparam name = "T"> specifies the object type to be serialized. The [Serializable] feature must be declared. </typeparam>
/// <Param name = "obj"> object to be serialized </param>
Public static string XmlSerialize <T> (T obj)
{
Using (MemoryStream MS = new MemoryStream ())
{
XmlSerializer serializer = new XmlSerializer (typeof (T ));
Serializer. serialized (MS, obj );
Ms. Seek (0, SeekOrigin. Begin );
Using (StreamReader reader = new StreamReader (MS, Encoding. UTF8 ))
{
Return reader. ReadToEnd ();
}
}
}
/// <Summary>
/// Use XmlSerializer to deserialize an object
/// </Summary>
/// <Param name = "xmlOfObject"> xml string to be deserialized </param>
Public static T XmlDeserialize <T> (string xmlOfObject) where T: class
{
Using (MemoryStream MS = new MemoryStream ())
{
Using (StreamWriter sr = new StreamWriter (MS, Encoding. UTF8 ))
{
Sr. Write (xmlOfObject );
Sr. Flush ();
Ms. Seek (0, SeekOrigin. Begin );
XmlSerializer serializer = new XmlSerializer (typeof (T ));
Return serializer. Deserialize (MS) as T;
}
}
}
# Endregion... remaining full text>
What are the problems with XmlSerializer serialization and deserialization?
[XmlRootAttribute ("Extensiondata", IsNullable = false)]
Public class Extensiondata
{
Public string MagnetPullStrength;
Public string MagnetGrade;
Public string VisibleCustomerID;
}
XmlSerializer serializer = new XmlSerializer (typeof (Extensiondata ));
TextWriter writer = new StreamWriter (CommonLogic. SafeMapPath ("images \ po. xml "));
Extensiondata po = new Extensiondata ();
Po. MagnetPullStrength = TextBox1.Text;
Po. MagnetGrade = TextBox2.Text;
Po. VisibleCustomerID = TextBox3.Text;
Serializer. Serialize (writer, po );
Writer. Close ();