针对不同的节点列表将多态XML序列化/反序列化为C#对象
我有一个这样的XML文件针对不同的节点列表将多态XML序列化/反序列化为C#对象,c#,xml,serialization,xml-serialization,C#,Xml,Serialization,Xml Serialization,我有一个这样的XML文件 <xml> <nodes> <text/> <img/> <text/> </nodes> </xml> 如果不需要带有类型声明的XmlArrayItem属性,只需将其添加到基类中即可: [Serializable] [XmlRoot ( "textfile" )] public class TextFile {
<xml>
<nodes>
<text/>
<img/>
<text/>
</nodes>
</xml>
如果不需要带有类型声明的XmlArrayItem属性,只需将其添加到基类中即可:
[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;
}
}
你调查过这个属性了吗?您可以使用它来转发声明基类的后代以进行序列化。我找到了一个更好的选项,但任何人都可以提供。@mtjin一个示例将非常有用。我还添加了我当前的代码更多,同样的问题,还有一些代码。
[Serializable]
[XmlInclude(typeof(NodeText))]
[XmlInclude(typeof(NodeImg))]
public class NodeBase
{}