序列化&将属性反序列化为 list<string>使用 C# 编写 xml 文件 [英] serialize & deserialize with property as list<string> xml file using C#
本文介绍了序列化&将属性反序列化为 list<string>使用 C# 编写 xml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何序列化 &使用 C# 反序列化以下 xml 文件.我已经为这个 xml 创建了可序列化的类.
How to serialize & deserialize below xml file using C#. I have created serializable class for this xml.
在反序列化这个 xml 的一些代码下面,列表只能获得单个值.
below some code to deserialize this xml, the list is able to get only single value.
<?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);
}
推荐答案
您的 XML 定义与您的模型不匹配.
Your XML definition does not match your models.
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<CSVFile>
<csvstrings>ff</csvstrings>
<csvstrings>gg</csvstrings>
<csvstrings>jj</csvstrings>
</CSVFile>
</Configuration>
它需要以下模型:
配置
CSV文件
Configuration
CSVFile
因此,您的实现应该是:
So, your implementation should be:
[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);
}
这篇关于序列化&amp;将属性反序列化为 list&lt;string>使用 C# 编写 xml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文