简体   繁体   English

反序列化:NullReferenceException

[英]Deserialization : NullReferenceException

I try to deserialize this XML document : 我尝试反序列化此XML文档:

<?xml version="1.0" encoding="us-ascii" ?> 
<message t="2013-08-05T11:45:45Z">
    <release>
        <rlse type="upg_fwr" value="EW_6_0s1_FR" /> 
        <rlse type="upg_sft_configframes" value="0" /> 
        <rlse type="upg_sft_config" value="0" /> 
    </release>
</message>

Here is the code I wrote. 这是我写的代码。 I have similar code which works perfectly, but in this case, the "ConfigurationElements" property is null after the deserialization process... The problem seems simple, but I don't see what maistake I did :-( Any idea ? 我有类似的代码,可以很好地工作,但是在这种情况下,反序列化过程之后,“ ConfigurationElements”属性为null ...这个问题似乎很简单,但是我看不到我做过的主要事情:-(知道吗?

[Serializable]
[XmlRoot("message")]
public class Message
{
    [XmlElement("release")]
    public ConfigurationElements ConfigurationElements { get; set; }
}

[Serializable]
public class ConfigurationElements
{
    public ConfigurationElements()
    {
        this.Items = new List<ConfigurationElement>();
    }

    [XmlElement("rlse")]
    public List<ConfigurationElement> Items { get; set; }
}

[Serializable]
public class ConfigurationElement
{
    [XmlAttribute("type")]
    public string Name { get; set; }

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

Edit : this is how I deserialize my message : 编辑:这是我反序列化消息的方式:

XmlReader reader;
XmlReaderSettings settings = new XmlReaderSettings {CheckCharacters = false, CloseInput = true};

reader = XmlReader.Create(
  new StringReader(xml),
  settings);

Message message;

using (reader)
{
    XmlSerializer serializer = new XmlSerializer(typeof(Message));

    try
    {
        message = (Message)serializer.Deserialize(reader);
    }
    catch(XmlException exc)
    {
        throw new MalformedDocumentException("The XML document is malformed.", exc);
    }
    catch(InvalidOperationException exc)
    {
        throw new MalformedDocumentException("The XML document is malformed.", exc);
    }
    catch(Exception exc)
    {
        throw new Exception(exc.Message, exc);
    }
}

// message is used here

A possible solution for your issue : 您的问题的可能解决方案:

// Change your Message's ConfigurationElements property with this
[XmlArray("release")]
[XmlArrayItem("rlse")]
public List<ConfigurationElement> ConfigurationElements { get; set; }

You'll be able to get rid of your mid-class ConfigurationElements and help the Xml parser. 您将可以摆脱中级的ConfigurationElements并帮助Xml解析器。

You should probably pass the Encoding as a parameter to the Serialization / Deserialization , could help. 您可能应该将Encoding作为参数传递给Serialization / Deserialization ,这可能会有所帮助。

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

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