views:

415

answers:

3

I have an Xml document that looks similar too

<Reports xmlns="">
  <Report>
    <ReportID>1</ReportID>
    <ParameterTemplate />
  </Report>
</Reports>

It fails serializing to this object

[XmlType(TypeName = "Report")]
public class Report
{
    [XmlElement("ReportID")]
    public int ID { get; set; }

    [XmlElement("ParameterTemplate")]
    public XElement ParameterTemplate { get; set; }
}

It's failing because the empty ParameterTemplate element, because if it contains child elements it deserializes fine.

How can I get this to work?

This is my Deserialization Code

var serializer = new XmlSerializer(typeof(Report));
return (Report)serializer.Deserialize(source.CreateReader());

The exception is

The XmlReader must be on a node of type Element instead of a node of type EndElement.

How can I get this to deserialize with the existing xml?

Thanks -c

+1  A: 

It looks like the content of XElement - if not null - cannot be an empty XML element. In other words, you would not be able to serialize that XML in your example from an in-memory representation/instance of your Report class.

Wim Hollebrandse
That's the conclusion I've come to, I've talked to the provider of that XML to remove null elements
Chad
A: 

You can implement IXmlSerializable interface on your report class and overwrite ReadXml and WriteXml methods.

Roland
A: 

Use IsNullable=True

[XmlType(TypeName = "Report")]
public class Report
{
    [XmlElement("ReportID")]
    public int ID { get; set; }

    [XmlElement("ParameterTemplate", IsNullable=true)]
    public XElement ParameterTemplate { get; set; }
}
sylvanaar
As mentioned in the comments above, this does *NOT* work.
Chad