XMLSerialization with no root element
I am trying to deserialize a relatively simple string in c# below. An XML
response is received from a REST API call. The response from the API is
being storing in a string because the built-in converter for the
Spring.Rest is failing to convert to an XMLDocument object so I am trying
to create a work around.
Here is the basic scenario.
//Response from API
string emaildata="<?xml version=\"1.0\" encoding=\"UTF-8\"
standalone=\"yes\"?>"
+"<email-address>xyz@gmail.com</email-address>";
//Code calling the conversion of the string
Console.WriteLine(xmlConversion.XmlDeserializeFromString(emaildata,typeof(email)).ToString());
//Object being Deserialized into
public class email
{
[System.Xml.Serialization.XmlElement("email-address")]
public string emailAddress { get; set; }
}
//Conversion Class
public static class xmlConversion
{
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
public static T XmlDeserializeFromString<T>(string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
}
Any help would be appreciated.
Thanks!
No comments:
Post a Comment