Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml Deserialization Fails on Empty Element

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

like image 697
CaffGeek Avatar asked Feb 04 '10 16:02

CaffGeek


People also ask

What is the correct way of using XML deserialization?

To deserialize the objects, call the Deserialize method with the FileStream as an argument. The deserialized object must be cast to an object variable of type PurchaseOrder . The code then reads the values of the deserialized PurchaseOrder .

What is XML Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization. Note this is the kind of thing I meant. You are not telling the XmlSerializer to ignore namespaces - you are giving it XML that has no namespaces.

What is XML ignore?

XmlIgnoreAttribute Class (System. Xml. Serialization) Instructs the Serialize(TextWriter, Object) method of the XmlSerializer not to serialize the public field or public read/write property value.


1 Answers

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.

like image 50
Wim Avatar answered Nov 15 '22 07:11

Wim