c# - 在 C# 中编写 XML 类
问题描述
我有一个这样的xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Devices>
<Settings>
<Name>ABC</DeviceName>
<HostNic>LAN_1</HostNic>
</Settings>
</Devices>
</Configuration>
我想将其反序列化为对象形式。我正在尝试为 xml 文件定义一个类结构,如下所示:
class Configuration
{
[XmlElement("Address")]
public List<Devices> deviceList = new List<Devices>();
}
class Devices
{
[XmlElement("Address")]
public List<Settings> settingList = new List<Settings>();
}
class Settings
{
public string Name { get; set; }
public string HostNic { get; set; }
}
有没有其他合适的方法来定义这个 xml 文件的类?
解决方案
您的类需要一些修改,特别是您添加的属性。
[XmlRoot]
public class Configuration
{
[XmlElement("Devices")]
public List<Devices> deviceList = new List<Devices>();
}
public class Devices
{
[XmlElement("Settings")]
public List<Settings> settingList = new List<Settings>();
}
public class Settings
{
public string Name { get; set; }
public string HostNic { get; set; }
}
然后您可以将 XML 反序列化为上述类:
var serializer = new XmlSerializer(typeof(Configuration));
using (System.IO.TextReader reader = new System.IO.StringReader(<Your XML String>))
{
Configuration config = (Configuration)serializer.Deserialize(reader);
}
推荐阅读
- c++ - 错误:'operator<<' 不匹配(操作数类型是 'std::ostream' {aka 'std::basic_ostream
'} 和 'std::_List_iterator ') - ubuntu - Conda config 显示的项目比配置的多
- python - 集成 keras LSTM 和 scikit boost
- jenkins - 如何在 Jenkins 上并行运行 jmeter 脚本
- java - 如何在spring boot中序列化和反序列化XML?
- javascript - 如何在 jquery 中为克隆 div 提供动态 id。如何为克隆 div 提供动态 id?
- asp.net-core-mvc - 根据文化和会话状态值加载资源文件
- css - 如何通过 ctrl 单击跳转到 VS 代码中的 css 文件?
- google-cloud-platform - 模拟演示数据流的经济有效的方法是什么
- haskell - 一个咖喱版的 union 折叠?