[英]Writing Xml Class in c#
I have a xml file like this: 我有一个这样的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>
I want to deserialize this to object form. 我想反序列化此对象形式。 I am trying to define a class structure for the xml file like this:
我正在尝试为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; }
}
Is there any other appropriate way of defining class for this xml file? 还有其他合适的方法来为此xml文件定义类吗?
Your Classes need some modifications, specially the attributes you have added. 您的班级需要一些修改,特别是您添加的属性。
[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; }
}
Then you can de-serialize the XML into the above classes: 然后,您可以将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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.