2013-08-06 124 views
0

默認XmlSerializer能夠將類屬性序列化爲Xml屬性嗎?類屬性的序列化?

[MyClassTypeAttribute(ClassType.MyClass)] 
public MyClass : BaseClass { 

} 

將轉向

<myclass MyClassType="MyClass"> 

原因

我有我發送不同的對象,通過相同的操作合同,全部來自BaseClass得出一個WCF服務。要知道它是哪種類型的對象並直接進行轉換(並將其序列化爲Xml以便在文檔中寫入後),我想要一些「type」屬性(enum)。

一種可能性是,當然,宣告財產XmlAttribute

[XmlAttribute(params)] 
public MyClassType { get; set; } 

這裏的問題是:該XmlSerializerDataContractSerializer爲好,據我所知)迫使我對每一個物業的setter。我知道我可以宣佈setterprotected,它仍然有效(XmlSerializer,你頑皮的小東西),但不真的喜歡這個解決方案,因爲1)我認爲有一個原因,我能夠省略二傳手在波蘇斯通常和2)聲明一些屬性爲XmlAttributes等,作爲XmlElements是混淆了(這就像把貓燉牛肉

(此外,是否有可能迫使派生類來聲明某些屬性?)

[abstract MyClassTypeAttribute] 

回答

0

如果它是關於您在這裏類的類型是一個例子:

[XmlIncludeAttribute(typeof(ConcreteFooOne))] 
    [XmlIncludeAttribute(typeof(ConcreteFooTwo))] 
    [XmlIncludeAttribute(typeof(ConcreteFooThree))] 
    [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] 
    public abstract partial class AbstractFoo 
    { 
    // Some abstract props etc. 
    } 

    [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] 
    public class ConcreteFooOne : AbstractFoo 
    { 
    public int MyProp { get; set; } 
    } 
    [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] 
    public class ConcreteFooTwo : AbstractFoo 
    { 

    } 
    [XmlRoot(ElementName = "FooData", Namespace = "http://foo.bar")] 
    public class ConcreteFooThree : AbstractFoo 
    { 

    } 

    class Program 
    { 
    static void Main(string[] args) 
    { 
     var serializer = new System.Xml.Serialization.XmlSerializer(typeof(AbstractFoo)); 
     using (var stream = new FileStream("test.txt", FileMode.OpenOrCreate)) 
     { 
     serializer.Serialize(stream, new ConcreteFooOne() { MyProp = 10 }); 
     stream.Flush(); 
     } 


     using (var stream = new FileStream("test.txt", FileMode.OpenOrCreate)) 
     { 
     var c = serializer.Deserialize(stream); 
     } 
    } 
    } 

的代碼將序列化和包括type屬性,當你反序列化,你會得到正確的實例。