xml序列化派生类
最近在搞谷歌地球二次开发,其中对kml文件的操作非常之频繁,kml符合xml的标准,所以在项目中会经常将对象序列化成xml,然后在调用LoadKmlData()方法加载到GoogleEarth,在开发过程中遇到这样的问题,A类中包含B类,B类是一个基类,B类派生出C、D类,在实际使用中A类中的B类实例化成C类或D类,但在序列化时得不到想要的结果,经过仔细研究解决问题,直接上代码。
A = KmlPlacemark;B = KmlBaseGraph;C = KmlPoint; D = KmlLineString
/// <summary>
/// 目标对象
/// </summary>
[XmlType(TypeName="Placemark")]
public class KmlPlacemark
{
/// <summary>
/// 目标对象ID
/// </summary>
[XmlAttribute]
public string id { get; set; }
/// <summary>
/// 对象名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 对象描述----可存放链接和图片
/// 如<![CDATA[<a href="http://www.baidu.com">www.baidu.com</a><img src="file:///C:/Users/Public/Pictures/Sample%20Pictures/head-4.jpg"/>]]>
/// </summary>
public string description { get; set; }
/// <summary>
/// 样式路径
/// </summary>
public string styleUrl { get; set; }
public KmlLookAt LookAt{get;set;}
/// <summary>
/// 模型
/// </summary>
public KmlModel Model { get; set; }
/// <summary>
/// 样式
/// </summary>
public KmlStyle Style { get; set; }
[XmlElement(typeof(KmlPoint))]
[XmlElement(typeof(KmlLineString))]
[XmlElement(typeof(KmlPolygon))]
public KmlBaseGraph Graph { get; set; }
}
KmlBaseGraph类
[Serializable] public class KmlBaseGraph { }
[XmlType(TypeName = "Point")] public class KmlPoint : KmlBaseGraph { /// <summary> /// 目标空间位置组合 /// </summary> public string coordinates { get; set; } }
/// <summary> /// 绘制图形的基本类 /// </summary> [XmlType(TypeName = "LineString")] public class KmlLineString : KmlBaseGraph { public int tessellate { get; set; } /// <summary> /// 线两点空间坐标位置组合 /// </summary> public string coordinates { get; set; } }
要注意KmlPlacemark类中红色部分代码,这里添加多个派生类元素类型,当在序列化时,就会根据当前派生类的对象,成不同的xml节点,这样就到达我想要的效果(同一个类实对象在实例化不同的派生类时,序列化的xml为不同的节点)。
结果1:
结果2: