【发布时间】:2011-11-12 21:37:08
【问题描述】:
我遇到了异常
The type KML.Placemark was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
当我尝试序列化我的对象时。我知道这个异常有两种不同的解决方案,但在这种情况下都不起作用。
一些背景:
我有一个紧跟 GoogleEarth/OpenGIS KML format 的类结构(用于在 GoogleEarth 上绘图)。
我的根类型是KMLDocument,其中包含一组KMLObjects:
public class KMLDocument
{
public KMLObject[] members;
}
而KMLObject 是Feature 的基本类型,它是Placemark 的基本类型
问题:
当我为 KMLDocument 构造序列化程序时,它不会直接知道像 Placemark 这样的派生类型,除非我明确告诉它。所以我这样做:
XmlSerializer serializer = new XmlSerializer(typeof(KMLDocument),
new Type[] { typeof(KMLObject),
typeof(Feature),
typeof(Placemark) } );
我还将属性附加到 KMLDocument 类以确保它知道所有重要类型:
[XmlRootAttribute("kml", Namespace="http://www.opengis.net/kml/2.2")]
[XmlInclude(typeof(KMLObject))]
[XmlInclude(typeof(Feature))]
[XmlInclude(typeof(Placemark))]
public class KMLDocument
{ .... }
但是,尽管以两种不同的方式告诉序列化程序Placemark,但当我调用
序列化,我得到了异常:
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!
}
如果我添加一个 Placemark 类型的虚拟变量,序列化程序突然可以找到该类型,并且它可以正常工作:
public class KMLDocument
{
public KMLObject[] members;
public Placemark dummy_var; // Should NOT be needed!
}
我错过了什么?为什么我的 XmlSerializer-Constructor 和我的属性都未能提供重要信息?
【问题讨论】:
-
我不明白为什么它不起作用。您是否尝试过调试 XmlSerializer 生成的程序集? hanselman.com/blog/…
-
@Martijn:我一直在寻找生成的程序集,但到目前为止一直找不到。
-
如 url 中所述,您不需要程序集,pdb en 源代码就可以了。另一种更复杂的方法是将进程转储到内存转储文件并使用 windbg 加载。然后您可以将动态加载的程序集保存到光盘并检查它。
标签: c# xml exception serialization