If you have the requirement to convert object of data into the XElement form, then here is the solution for the same. the below piece of code will give output in the form of XElement by serializing the object of the class.
This method takes input as object and cast this with the class as of type "T" and returns the output into XElement format.
XElement ToXElement<T>(object objectToSerialize)
{
try
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
var xmlSerializerNamespace = new XmlSerializerNamespaces();
// To make namespace empty
xmlSerializerNamespace.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(streamWriter, objectToSerialize, xmlSerializerNamespace);
xElement = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
}
catch (Exception ex)
{
xElement = null;
}
return xElement;
}
This method takes input as object and cast this with the class as of type "T" and returns the output into XElement format.
XElement ToXElement<T>(object objectToSerialize)
{
try
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
var xmlSerializerNamespace = new XmlSerializerNamespaces();
// To make namespace empty
xmlSerializerNamespace.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(streamWriter, objectToSerialize, xmlSerializerNamespace);
xElement = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
}
catch (Exception ex)
{
xElement = null;
}
return xElement;
}
No comments:
Post a Comment
Put your comments here