如何反序列化Xml?

How to deserialize Xml?

美好的一天! 我有简单的 xml 字符串(测试服务器响应):

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

我创建可序列化 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-序列化助手:

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

所以,我的代码:

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

但我有空值(或 Int32 为零)。 拜托,你能帮我解决这个问题吗? 谢谢!

success 是属性,不是元素。您没有向我们展示 variant 的定义,但是 confidencevariant 中的一个属性,而不是一个元素。

这些 类 应该有效:

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