开发者

Why deserialize XML into Object return null value?

开发者 https://www.devze.com 2023-01-26 23:56 出处:网络
I have a XML string 开发者_运维问答like that: <?xml version=\"1.0\" ?> <result> <vmeet_id>7121</vmeet_id>

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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消