2
我有以下XML文件格式。我想反序列化到對象中,但它不起作用。在反序列化「字段」時出現問題。XML反序列化:使用列表
<ExportDefinition>
<DestinationDir>C:\Export\</DestinationDir>
<LevelID>102</LevelID>
<Metadata>
<Field>
<Source>CreateDate</Source>
<DataType>DateTime</DataType>
<Field>
<Field>
<Source>UserName</Source>
<DataType>Text</DataType>
<Field>
</Metadata>
</ExportDefinition>
static void Main(string[] args)
{
string xmlFile = @"C:\cobra_exp_def.xml";
FileStream ReadFileStream = new FileStream(xmlFile, FileMode.Open, FileAccess.Read, FileShare.Read);
XmlSerializer SerializerObj = new XmlSerializer(typeof(ExportDefinition));
ExportDefinition LoadedObj = (ExportDefinition)SerializerObj.Deserialize(ReadFileStream);
ReadFileStream.Close();
}
public class ExportDefinition
{
[XmlElement]
public string DestinationDir { get; set; }
[XmlElement]
public string LevelID { get; set; }
}
public class Metadata
{
private List<Field> list = new List<Field>();
[XmlElement]
public List<Field> Metadata { get { return list; } set { list = value; } }
}
public class Field
{
[XmlElement]
public string Source { get; set; }
[XmlElement]
public string DataType { get; set; }
}
解決方案
最後設法將其與以下工作:[XmlArray("Metadata"), XmlArrayItem("Field", typeof(Field))]
public List<Field> Metadata
{
get { return (_fields); }
set { _fields = value; }
}
private List<Field> _fields = new List<Field>();
「錯誤CS0542:‘元數據’:成員名稱不能與它們的封閉類型」 - 顯示代碼不編譯......這可以讓答案不可靠 –