2013-05-27 66 views
0

我有4個實體類。 A,B,C,D。它具有不同的屬性,如ID,地址,甚至複雜的類型。我想編寫一個通用的方法,我可以通過任何列表,它會轉換爲XML。比方說將任何類型的列表序列化爲XML?

public string GetAnyListtoXML(Any type of list) 
     { 
      string myXML=string.Empty; 

return myXML; 
     } 

回答

1

這個方法允許你序列化任何你想要的。 你的實體類應該有無參數的構造函數。

此鏈接可能有助於控制序列:http://msdn.microsoft.com/en-us/library/2baksw0z%28v=vs.100%29.aspx

public string ObjectToXml<T>(T obj) 
    { 
     var stream = new StringWriter(); 

     string xmlDoc = string.Empty; 
     try 
     { 
      var xmlSerializer = new XmlSerializer(typeof (T)); 
      xmlSerializer.Serialize(stream, obj); 
      xmlDoc = stream.GetStringBuilder().ToString(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Błąd pliku xml: " + ex); 
     } 
     finally 
     { 
      stream.Close(); 
     } 
     return xmlDoc; 
    } 



    public static T XmlToObject<T>(string xmlDoc) 
    { 
     var stream = new MemoryStream(); 
     byte[] xmlObject = Encoding.Unicode.GetBytes(xmlDoc); 

     stream.Write(xmlObject, 0, xmlObject.Length); 
     stream.Position = 0; 
     T message; 

     var ss = new XmlSerializer(typeof (T)); 
     try 
     { 
      message = (T) ss.Deserialize(stream); 
     } 
     catch (Exception) 
     { 
      message = default(T); 
     } 
     finally 
     { 
      stream.Close(); 
     } 
     return message; 
    } 

如果你想這種方法只需要列表,你可以使用它:

public string ObjectToXml<T>(List<T> obj) 
    { 
     var stream = new StringWriter(); 

     string xmlDoc = string.Empty; 
     try 
     { 
      var xmlSerializer = new XmlSerializer(typeof (List<T>)); 
      xmlSerializer.Serialize(stream, obj); 
      xmlDoc = stream.GetStringBuilder().ToString(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Błąd pliku xml: " + ex); 
     } 
     finally 
     { 
      stream.Close(); 
     } 
     return xmlDoc; 
    }