2011-07-04 24 views
8

Có ai biết làm thế nào tôi (hoặc nếu nó có thể) đảo ngược XML tôi là tạo ra bên dướiSerialize Danh sách <T> to XML, và ngược lại XML để Liệt kê <T>

[Serializable()] 
public class CustomDictionary 
{ 
    public string Key { get; set; } 
    public string Value { get; set; } 
} 

public class OtherClass 
{ 
    protected void BtnSaveClick(object sender, EventArgs e) 
    { 
     var analysisList = new List<CustomDictionary>(); 

     // Here i fill the analysisList with some data 
     // ... 

     // This renders the xml posted below 
     string myXML = Serialize(analysisList).ToString(); 
     xmlLiteral.Text = myXML; 
    } 

    public static StringWriter Serialize(object o) 
    { 
     var xs = new XmlSerializer(o.GetType()); 
     var xml = new StringWriter(); 
     xs.Serialize(xml, o); 

     return xml; 
    } 
} 

Các xml render

<?xml version="1.0" encoding="utf-16"?> 
<ArrayOfCustomDictionary xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <CustomDictionary> 
    <Key>Gender</Key> 
    <Value>0</Value> 
    </CustomDictionary> 
    <CustomDictionary> 
    <Key>Height</Key> 
    <Value>4</Value> 
    </CustomDictionary> 
    <CustomDictionary> 
    <Key>Age</Key> 
    <Value>2</Value> 
    </CustomDictionary> 
</ArrayOfCustomDictionary> 

Bây giờ, sau một vài giờ Googling và cố gắng tôi đang mắc kẹt (rất có thể bộ não của tôi đã có một số kỳ nghỉ đã). Bất cứ ai có thể giúp tôi làm thế nào để đảo ngược xml này trở lại một danh sách?

Cảm ơn

+0

mới XmlSerializer (o.GetType()) Deserialize (.. .) –

+0

Bạn có thực sự cần một từ điển tùy chỉnh không? Từ điển chung có thể có bất kỳ loại nào làm khóa và giá trị. –

Trả lời

14

Chỉ deserialize nó:

public static T Deserialize<T>(string xml) { 
    var xs = new XmlSerializer(typeof(T)); 
    return (T)xs.Deserialize(new StringReader(xml)); 
} 

Sử dụng nó như thế này:.

var deserializedDictionaries = Deserialize<List<CustomDictionary>>(myXML); 
Các vấn đề liên quan