2010-06-24 132 views
4

我需要幫助,我有一些數據進來的XML,我想做一個對象,做一些事情,將它序列化併發送出去... 但它必須是某種自定義序列化。自定義xml序列化

XML,如:

<Animals Ver="12" class="1" something="2"> 
    <Dog Ver="12" class="2" something="17"> 
     <Name> a </Name> 
     <Sound> oof </Sound> 
     <SomeOtherProp>12</SomeOtherProp> 

    </Dog> 
    <Cat Ver="12" class="3" something="4"> 
     <Name> b </Name> 
     <Sound> meow </Sound> 
    </Cat> 
</Animals> 

需求將呈現爲:

abstract class Animal :XmlMagic 
{ 
    public string Name{get;set;} 
    public string Sound{get;set;} 

    public void SomeMagicalXMLSerializationMethod() 
    {} 
    public void SomeMagicalXMLDeSerializationMethod() 
    {} 
} 

class Dog: Animal, XmlMagic 
{ 
    public int SomeOtherProp{get;set;} 
    public void SomeMagicalXMLSerializationMethod() 
    {} 
    public void SomeMagicalXMLDeSerializationMethod() 
    {} 
} 

回答

4

但也有XML序列化的屬性,如

[XmlAttribute] 
[XmlArrayElement] 
[XmlRoot] 

等,你甚至可以使用這些屬性來控制自己的序列化和acheive你想要什麼,而無需編寫複雜的序列化邏輯。

0

您可能想查看WCF REST Starter Kit;因爲它包含一個名爲「將XML粘貼爲類型」的視覺工作室添加內容

基本上,您複製原始XML,然後選擇該選項;它會根據該XML爲您生成一個類。然後你可以做一些簡單的事情:

var xmlResponse = new XmlDocument(); 
xmlResponse.LoadXml(response); 
var deserializedResponse = ConvertNode<ResponseWrapper.response>(xmlresponse); 

public static T ConvertNode<T>(XmlNode node) where T : class 
     { 
      var stm = new MemoryStream(); 

      var stw = new StreamWriter(stm); 
      stw.Write(node.OuterXml); 
      stw.Flush(); 

      stm.Position = 0; 

      var ser = new XmlSerializer(typeof(T)); 
      var result = (ser.Deserialize(stm) as T); 

      return result; 
     }