2015-04-22 62 views
0

我用xml序列化,我只用一個簡單的類來工作,但是當我創建了一個輔助類時,其中的簡單類只是一個組件,序列化停止工作。它在序列化階段出現「錯誤反射類型」錯誤。代碼如下:XML序列化:一個類內的類

public class CustomField 
{ 
    [XmlAttribute("FieldID")] 
    public string FieldID; 
    [XmlAttribute("FieldValue")] 
    public string FieldValue; 
    public CustomField() { } 
    public CustomField(string fieldID, string fieldValue) 
    { 
     this.FieldID = fieldID; 
     this.FieldValue = fieldValue; 
    } 
} 
[XmlType("Entry")] 
public class CustomEntry 
{ 
    [XmlAttribute("Author")] 
    public string Author; 
    [XmlAttribute("Title")] 
    public string Title; 
    [XmlAttribute("Trial")] 
    public string Trial; 
    [XmlAttribute("Responses")] 
    public List<CustomField> Responses; 
    public CustomEntry() { } 
} 
public static class EntrySerializer 
{ 
    public static void SerializeObject(this CustomEntry entry, string file) 
    { 
     var serializer = new XmlSerializer(typeof(CustomEntry)); 
     using (var stream = File.OpenWrite(file)) 
     { 
      serializer.Serialize(stream, entry); 
     } 
    } 
} 

它是Xml標記的標籤問題還是其他的東西?

+0

沒關係,標籤需要 「的XmlElement」 的名單。 – bordeo

回答

0

嘗試定義你這樣的串行:

var serializer = new XmlSerializer(typeof(CustomEntry), new Type[] { typeof(CustomField) }); 

您需要通知的其他類型則期待序列化的串行器。

0

我通常使用XMLRoot標記(兩個地方)。我需要看到XML的示例以提供更好的答案。

[XmlRoot("CustomField")] 
 
public class CustomField 
 
{ 
 
    [XmlAttribute("FieldID")] 
 
    public string FieldID; 
 
    [XmlAttribute("FieldValue")] 
 
    public string FieldValue; 
 
    public CustomField() { } 
 
    public CustomField(string fieldID, string fieldValue) 
 
    { 
 
     this.FieldID = fieldID; 
 
     this.FieldValue = fieldValue; 
 
    } 
 
} 
 
[XmlRoot("Entry")] 
 
public class CustomEntry 
 
{ 
 
    [XmlAttribute("Author")] 
 
    public string Author; 
 
    [XmlAttribute("Title")] 
 
    public string Title; 
 
    [XmlAttribute("Trial")] 
 
    public string Trial; 
 
    [XmlAttribute("Responses")] 
 
    public List<CustomField> Responses; 
 
    public CustomEntry() { } 
 
} 
 
​