Why deserialize XML into Object return null value?

我是研究僧i 提交于 2021-02-11 16:54:47

问题


I have a XML string like that:

<?xml version="1.0" ?>
<result>
<vmeet_id>7121</vmeet_id>
<username>MT_Hue_QuangBinh_QuangTri</username>
<email></email>
<begin_date>2010-04-21 08:53</begin_date>
<expiry_date>2010-12-21 00:00</expiry_date>
<point></point>
<info>OK</info>
</result>

I want to deserialize it into an object, so I created this class:

[Serializable] 
[XmlRoot(ElementName = "result", IsNullable = false)]
public class UserInfo
{
    [XmlAttribute("vmeet_id")]
    public int UserID { get; set; }
    [XmlAttribute("username")]
    public string Username { get; set; } 
    [XmlAttribute("email")]
    public string Email { get; set; }
    [XmlAttribute("begin_date")]
    public DateTime BeginDate { get; set; }
    [XmlAttribute("expiry_date")]
    public DateTime ExpiryDate { get; set; }
    [XmlAttribute("point")]
    public string Point { get; set; }
    [XmlAttribute("info")]
    public string Info { get; set; }
}

and then use this code to deserialize:

var deserializer = new XmlSerializer(typeof(UserInfo));
        using (var stream = new StringReader(result))
        {
            UserInfo userInfo = (UserInfo)deserializer.Deserialize(stream);
            return userInfo;
        }

return value was not null, but all its properties was null value:

<result vmeet_id="0" begin_date="0001-01-01T00:00:00" expiry_date="0001-01-01T00:00:00"/>

what is wrong here? Did I forgot something?

Thank you.


回答1:


In your XML, all your 'vmeet' 'begin_date' are all elements, but in your UserInfo Class, you declare them as XMLAttribute. Try changing them to XMLElement should help.




回答2:


Use XmlDocument and Json to easily resolve result.

        public static T XmlToModel<T>(string xml)
        {

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string jsonText = JsonConvert.SerializeXmlNode(doc);

            T result = JsonConvert.DeserializeObject<T>(jsonText);

            return result;
        }


来源:https://stackoverflow.com/questions/4252225/why-deserialize-xml-into-object-return-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!