I want to serialize an object to XML, but I don\'t want to save it on the disk. I want to hold it in a XElement variable (for using with LINQ), and then Deserialize back to
ToXelement without Code Analysis issues, same answer as Abdul Munim but fixed the CA issues (except for CA1004, this cannot be resolved in this case and is by design)
public static XElement ToXElement(this object value)
{
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
memoryStream = null;
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, value);
return XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
finally
{
if (memoryStream != null)
{
memoryStream.Dispose();
}
}
}