user2545071
user2545071

Reputation: 1410

How to deserialize Xml?

Good day! I have simple xml string (test for server response):

public static String GetTextXmlStringResponse()
     { 
          var result= "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
"<recognitionResults success=\"1\">"+
  "<variant confidence=\"1\">text text</variant>"+
"</recognitionResults>";
        return result;
    }

I create serializable class:

[Serializable()]
public class recognitionResults
{
    [System.Xml.Serialization.XmlElement("success")]
    public Int32 success { get; set; }

    [System.Xml.Serialization.XmlElement("confidence")]
    public variant confidence { get; set; }

    public recognitionResults()
    { }
}

Class-helper for serialize:

public class XmlUtility
{

    /// <summary>
    /// Serialize object  to XML string
    /// </summary>
    public static string Obj2XmlStr(object obj)
    {
        if (obj == null) return string.Empty;
        XmlSerializer sr = new XmlSerializer(obj.GetType());
        StringBuilder sb = new StringBuilder();
        StringWriter w = new StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture);
        sr.Serialize(
              w,
              obj);
        return sb.ToString();
    }

    /// <summary>
    /// Deserialize  XML string into object
    /// </summary>
    /// <param name="xml"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static T XmlStr2Obj<T>(string xml)
    {
        if (xml == null) return default(T);
        if (xml == string.Empty) return (T)Activator.CreateInstance(typeof(T));

        StringReader reader = new StringReader(xml);
        XmlSerializer sr = new XmlSerializer(typeof(T));//SerializerCache.GetSerializer(type);
        return (T)sr.Deserialize(reader);
    }
}

So, my code:

 var res = XmlUtility.XmlStr2Obj<recognitionResults>(GetTextXmlStringResponse());

But i have null values (or zero for Int32). Please, can you help me to fix that? Thank you!

Upvotes: 0

Views: 114

Answers (1)

Charles Mager
Charles Mager

Reputation: 26223

success is an attribute, not an element. You haven't shown us what variant is defined as, but confidence is an attribute within variant, not an element.

These classes should work:

[XmlRoot("recognitionResults")]    
public class RecognitionResults
{
    [XmlAttribute("success")]
    public int Success { get; set; }

    [XmlElement("variant")]
    public Variant Variant { get; set; }
}

public class Variant
{
    [XmlAttribute("confidence")]
    public int Confidence { get; set; }

    [XmlText]
    public string Value { get; set; }
}

Upvotes: 1

Related Questions