【问题标题】:Deserialization : NullReferenceException反序列化:NullReferenceException
【发布时间】:2013-12-02 15:01:04
【问题描述】:

我尝试反序列化这个 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>

这是我写的代码。我有类似的代码可以完美运行,但在这种情况下,“ConfigurationElements”属性在反序列化过程后为空......问题看起来很简单,但我看不出我做了什么 :-( 有什么想法吗?

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

编辑:这就是我反序列化消息的方式:

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

【问题讨论】:

  • 它可以在我的测试环境中正确反序列化。显示您的反序列化代码。
  • 我的评论在您修改后仍然适用。
  • 我还可以确认上述代码正确反序列化了呈现的数据(所有属性及其内部值)。
  • 我还使用此代码构建了一个项目,它运行良好。

标签: c# .net serialization xml-deserialization


【解决方案1】:

您的问题的可能解决方案:

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

您将能够摆脱您的中级ConfigurationElements 并帮助 Xml 解析器。

您可能应该将编码作为参数传递给序列化/反序列化,这可能会有所帮助。

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2012-03-17
    相关资源
    最近更新 更多