如何序列化&使用C#反序列化xml文件。 我为这个xml创建了可序列化的类。
在某些代码下面反序列化这个xml,列表只能获得单个值。
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<CSVFile>
<string>ff</string>
<string>gg</string>
<string>jj</string>
</CSVFile>
</Configuration>
[Serializable, XmlRoot("Configuration"), XmlType("Configuration")]
public class Configuration
{
public Configuration()
{
CSVFile = new List<string>();
}
[XmlElement("CSVFile")]
public List<string> CSVFile { get; set; }
}
public class Mytutorial
{
string configFilePath = "above xml file path"
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
FileStream xmlFile = new FileStream(configFilePath, FileMode.Open);
Configuration con = (Configuration)serializer.Deserialize(xmlFile);
}
答案 0 :(得分:4)
如下所示更改您的课程,它会正常工作
public class Configuration
{
[XmlArray("CSVFile")]
public List<string> CSVFile { get; set; }
}
答案 1 :(得分:4)
您的XML定义与您的模型不匹配。
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<CSVFile>
<csvstrings>ff</csvstrings>
<csvstrings>gg</csvstrings>
<csvstrings>jj</csvstrings>
</CSVFile>
</Configuration>
需要以下型号:
配置
CSVFile
所以,你的实现应该是:
[Serializable]
public class CSVFile
{
[XmlElement("csvstrings")]
public List<string> csvstrings { get; set; }
public CSVFile()
{
}
}
[Serializable, XmlRoot("Configuration"), XmlType("Configuration")]
public class Configuration
{
public Configuration()
{
}
[XmlElement("CSVFile")]
public CSVFile csvs { get; set; }
}
public class Mytutorial
{
string configFilePath = "above xml file path"
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
FileStream xmlFile = new FileStream(configFilePath, FileMode.Open);
Configuration con = (Configuration)serializer.Deserialize(xmlFile);
}