【发布时间】:2012-02-21 12:26:09
【问题描述】:
我有一个这样的 XML 文件
<xml>
<nodes>
<text/>
<img/>
<text/>
</nodes>
</xml>
我想将 C# 对象映射到这个对象,我知道如何使用 XmlArrayItem 但仅限于数组中只有一种项目类型的情况。我在考虑如何使用 img 和 text 节点的基类来做到这一点。但是任何人都可以显示我的 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;
}
}
【问题讨论】:
-
您查看过XmlInclude 属性吗?您可以使用它来前向声明基类的后代以进行序列化。
-
我找到了stackoverflow.com/questions/4071639/…,但谁能带来更好的选择。
-
@mtjin 举个例子会很有帮助。
-
我还添加了我当前的代码
-
更多here,同样的问题,还有一些代码。
标签: c# xml serialization xml-serialization