如何反序列化Xml?

时间:2015-04-15 11:39:33

标签: c# xml xml-serialization xml-deserialization

美好的一天! 我有简单的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;
    }

我创建了可序列化的类:

[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()
    { }
}

序列化的类助手:

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为零)。 拜托,你能帮我解决这个问题吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

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