I am writing common functions to serialize the given object and List<object> as follows
public string SerializeObject(Object pObject)// for given object
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(pObject));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e) { System.Console.WriteLine(e); return null; }
}
public string SerializeObject(List<Object> pObject)// for given List<object>
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(pObject));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e) { System.Console.WriteLine(e); return null; }
}
first one is working fine. If I pass any type, it is successfully returning xml string.
CORRECTION: Compilation error has occurred for second one (Error: cannot convert from List<MyType>
to List<object>
.
I rewrite the second one as follows which solves my problem. Now it is serializing the given List<generic types>
.
private string SerializeObject<T>(T source)
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, source);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
string XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
https://weblogs.asp.net/rajbk/Contents/Item/Display/345
The relevant code from the article:
private static string SerializeObject<T>(T source)
{
var serializer = new XmlSerializer(typeof(T));
using (var sw = new System.IO.StringWriter())
using (var writer = XmlWriter.Create(sw))
{
serializer.Serialize(writer, source);
return sw.ToString();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With