简体   繁体   English

XML序列化程序在对象反序列化时返回null

[英]XML serializer returns null on object deserialization

I have a stored procedure in the database which returns an XML stream, and the application deserializes that stream into its corresponding object. 我在数据库中有一个存储过程,它返回一个XML流,应用程序将该流反序列化为相应的对象。 The stored procedure is defined like this (I simplified it to make it more readable): 存储过程是这样定义的(我简化了它以使其更具可读性):

SELECT 
    usrs.FirstName AS 'FirstName',
    usrs.LastName AS 'LastName',
    usrs.Username AS 'Username',
    usrs.DateJoined AS 'DateJoined'
FROM USERS AS usrs
WHERE usrs.Username = @username
FOR XML PATH('UserProfile')

Notice that Username is a primary key, so the stored procedure will return only one result. 请注意, Username是主键,因此存储过程将只返回一个结果。 A sample query result would look like this: 示例查询结果如下所示:

<UserProfile>
  <FirstName>Chuck</FirstName>
  <LastName>Norris</LastName>
  <Username>chuck.awesome</Username>
  <DateJoined>2013-07-22T06:58:00</DateJoined>
</UserProfile>

Now in the application, this is how I get and deserialize the data: 现在在应用程序中,这是我获取和反序列化数据的方式:

internal static T GetData<T>(StoredProcedures storedProcedure, ParameterList parameters)
    {
        using (var connection = GetSqlConnection())
        {
            using (var command = new SqlCommand(storedProcedure.ToString(), connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;

                foreach (var parameter in parameters)
                {
                    command.Parameters.Add(new SqlParameter(parameter.Key.ToString(), parameter.Value));
                }

                connection.Open();

                var data = command.ExecuteScalar();

                return DeserializeXml<T>(data.ToString());
            }
        }
    }

And the DeserializeXML<T>() method: DeserializeXML<T>()方法:

private static T DeserializeXml<T>(string xmlStream, Type[] additionalTypes = null)
    {
        XmlSerializer serializer;

        if (additionalTypes == null)
        {
            serializer = new XmlSerializer(typeof(T));
        }
        else
        {
            serializer = new XmlSerializer(typeof(T), additionalTypes);
        }

        using (StringReader reader = new StringReader(xmlStream))
        {
            return (T)serializer.Deserialize(reader);
        }
    }

And finally the UserProfile class: 最后是UserProfile类:

[XmlRoot("UserProfile")]
[Serializable]
public class UserProfile
{
    public UserProfile()
    {
    }

    [XmlAttribute("Username")]
    public string Username { get; set; }

    [XmlAttribute("FirstName")]
    public string FirstName { get; set; }

    [XmlAttribute("LastName")]
    public string LastName { get; set; }

    [XmlAttribute("DateJoined")]
    public DateTime DateJoined { get; set; }
}

Now when I run the application, I see that the stored procedure returns the expected value, however, the serializer returns a UserProfile object with all fields set to null (except for the DateJoined field, which is set to the default value since it's not nullable). 现在,当我运行应用程序时,我看到存储过程返回了预期的值,但是,序列化程序返回一个UserProfile对象,所有字段都设置为nullDateJoined字段除外,该字段设置为默认值,因为它不可为空)。 Any idea what could be going wrong? 什么可能出错? I suspect it might be the XmlRoot() attribute in the UserProfile object, but then again the serializer doesn't throw any exception which is why I'm confused. 我怀疑它可能是UserProfile对象中的XmlRoot()属性,但是再次序列化程序不会抛出任何异常,这就是为什么我感到困惑。 Any idea what might be going wrong? 知道可能出了什么问题吗? Thanks in advance. 提前致谢。

您已使用[XmlAttribute]标记了属性,但xml将这些值包含为元素而非属性。

I had the same problem of deserialization being returned as null. 我有同样的问题,反序列化返回为null。 I had wrongly typed the Element name as below [XmlElement(ElementName = "fname")] 我错误地键入了元素名称,如下所示[XmlElement(ElementName =“fname”)]

The correct one was - [XmlElement(ElementName = "firstname")] 正确的是 - [XmlElement(ElementName =“firstname”)]

Just as FYI if anybody does this mistake. 就像FYI一样,如果有人犯了这个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM