2012-02-21 145 views
0

的名單我有這樣多態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; 
    } 
} 
+0

你有沒有看過[XmlInclude](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute.aspx)屬性?你可以用它來前向聲明你的基類的後代進行序列化。 – mtijn 2012-02-21 12:28:04

+0

我發現http://stackoverflow.com/questions/4071639/polymorphic-xml-serialization-deserialization但任何人都可以帶來更好的選擇。 – ambhai 2012-02-21 12:30:31

+0

@mtjin一個例子會很有幫助。 – ambhai 2012-02-21 13:17:17

回答

1

據我所知,你不需要用類型聲明的XmlArrayItem屬性,只需添加到您的基類:

[Serializable] 
[XmlInclude(typeof(NodeText))] 
[XmlInclude(typeof(NodeImg))] 
public class NodeBase 
{}