我有以下 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>();