I’m getting an exception
The type KML.Placemark was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
When I try to serialize my objects. I know of two different solutions to this exception, but neither is working in this case.
Some background:
I have a Class-structure that closely follows the GoogleEarth/OpenGIS KML format (for drawing on top of GoogleEarth).
My root type is KMLDocument which contains a set of KMLObjects:
public class KMLDocument
{
public KMLObject[] members;
}
And KMLObject is the base-type for Feature, which is the base-type for Placemark
The Problem:
When I construct the serializer for KMLDocument, it won’t directly know about derived types like Placemark unless I explicitly tell it. So I do it this way:
XmlSerializer serializer = new XmlSerializer(typeof(KMLDocument),
new Type[] { typeof(KMLObject),
typeof(Feature),
typeof(Placemark) } );
I also attach Attributes to the KMLDocument class to make sure it knows about all important types:
[XmlRootAttribute("kml", Namespace="http://www.opengis.net/kml/2.2")]
[XmlInclude(typeof(KMLObject))]
[XmlInclude(typeof(Feature))]
[XmlInclude(typeof(Placemark))]
public class KMLDocument
{ .... }
But, despite telling the serializer about Placemark two different ways, when I call
serialize, I get the exception:
static void Main(string[] args)
{
KMLDocument kml = new KMLDocument();
kml.AddPlacemark("MyPlacemark", "MyTest");
XmlSerializer serializer = new XmlSerializer(typeof(KMLDocument),
new Type[] { typeof(KMLObject),
typeof(Feature),
typeof(Placemark) } );
serializer.Serialize(new StreamWriter("MyKML.kml"), kml); // Exception on this line!
}
If I add a dummy-variable of type Placemark, suddenly the serializer can find the type, and it works right:
public class KMLDocument
{
public KMLObject[] members;
public Placemark dummy_var; // Should NOT be needed!
}
What am I missing? Why are both my XmlSerializer-Constructor and my Attributes failing to provide the important information?
Placemark and Feature are subclasses of KMLObject. The
membersfield holds a mixed array of Placemarks and Features.The
membersfield has to be tagged with an XmlArrayItemAttribute in order to specify that the elements it contains are polymorphic.http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx