Search code examples
c#xml-deserialization

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 stored 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;
    } 
}

Solution

  • Try changing the definition of the class to:

    [System.Xml.Serialization.XmlRoot("email-address")]
    public class email
    {
        [System.Xml.Serialization.XmlText()]
        public string emailAddress { get; set; }
    
    }