首页 > 解决方案 > 在 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 文件的类?

标签: c#xmlserialization

解决方案


您的类需要一些修改,特别是您添加的属性。

[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);
}

推荐阅读