Pregunta

I try to deserialize this XML document :

<?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 ?

[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
¿Fue útil?

Solución

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.

You should probably pass the Encoding as a parameter to the Serialization / Deserialization, could help.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top