多态XML序列化/反序列化到C#对象的不同节点
问题描述:
的名单我有这样多态XML序列化/反序列化到C#对象的不同节点
<xml>
<nodes>
<text/>
<img/>
<text/>
</nodes>
</xml>
我要地图C#对象这一个XML文件,我知道如何使用XmlArrayItem但只有柜面那里只是数组中的一个项目类型。我正在考虑如何使用基类来处理img和文本节点。但任何人都可以显示我的C#属性代码,我可以使用它自动将这个xml的序列化到C#对象中。不需要使用LINQ。
这里是我计划如何做,但它不工作:
[Serializable]
[XmlRoot ("textfile")]
public class TextFile
{
[XmlArray ("nodes")]
[XmlArrayItem ("text", typeof(NodeText)), XmlArrayItem ("img", typeof(NodeImg))]
public List<NodeBase Nodes
{
get;
set;
}
}
[Serializable]
public class NodeBase
{
}
[Serializable]
public class NodeText : NodeBase
{
[XmlText]
public String CDataContent
{
get;
set;
}
}
[Serializable]
public class NodeImg : NodeBase
{
[XmlAttribute ("width")]
public Int32 Width
{
get;
set;
}
[XmlAttribute ("height")]
public Int32 Height
{
get;
set;
}
[XmlAttribute ("src")]
public String SourceImgStr
{
get;
set;
}
}
答
据我所知,你不需要用类型声明的XmlArrayItem属性,只需添加到您的基类:
[Serializable]
[XmlInclude(typeof(NodeText))]
[XmlInclude(typeof(NodeImg))]
public class NodeBase
{}
你有没有看过[XmlInclude](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute.aspx)属性?你可以用它来前向声明你的基类的后代进行序列化。 – mtijn 2012-02-21 12:28:04
我发现http://*.com/questions/4071639/polymorphic-xml-serialization-deserialization但任何人都可以带来更好的选择。 – ambhai 2012-02-21 12:30:31
@mtjin一个例子会很有帮助。 – ambhai 2012-02-21 13:17:17