Https://www.cnblogs.com/servant/p/4462446.html
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Xml.Serialization;
Using System.IO;
Using System.Xml;
Namespace Common
{
public class Xmlutility
{
<summary>
Serializing a custom object to an XML string
</summary>
<param name= "MyObject" > Custom object Entities </param>
<returns> Serialized XML string </returns>
public static string serializetoxml<t> (T myObject)
{
if (myObject! = null)
{
XmlSerializer xs = new XmlSerializer (typeof (T));
MemoryStream stream = new MemoryStream ();
XmlTextWriter writer = new XmlTextWriter (stream, Encoding.UTF8);
Writer. formatting = formatting.none;//Indent
Xs. Serialize (writer, myObject);
Stream. Position = 0;
StringBuilder sb = new StringBuilder ();
using (StreamReader reader = new StreamReader (stream, Encoding.UTF8))
{
String line;
while (line = reader. ReadLine ()) = null)
{
Sb. Append (line);
}
Reader. Close ();
}
Writer. Close ();
Return SB. ToString ();
}
return string. Empty;
}
<summary>
Deserializing an XML string into an object
</summary>
<typeparam name= "T" > Object type </typeparam>
<param name= "xml" >xml characters </param>
<returns></returns>
public static T deserializetoobject<t> (string xml)
{
T MyObject;
XmlSerializer serializer = new XmlSerializer (typeof (T));
StringReader reader = new StringReader (XML);
MyObject = (T) serializer. Deserialize (reader);
Reader. Close ();
return myObject;
}
}
}
C # XML and objects are converted to each other