Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

c# - Why deserialize XML into Object return null value?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...