我有一个属于自定义类“设备”的对象列表,该对象已序列化为XML文件。 “设备”类具有一个嵌套的类,称为“功能”。
<ArrayOfDevice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Device>
<Name>CellaTemp PA</Name>
<Type>DeviceX</Type>
<Station>2</Station>
<Function>
<Name>Function1</Name>
</Function>
</Device>
<Device>
<Name>EKU1 KR</Name>
<Type>DeviceY</Type>
<Station>1</Station>
<Function>
<Name>Function2</Name>
</Function>
现在,我想在新的C#解决方案中打开此XML文件“ /.../DevicesXML”,并将其反序列化为包含“ Device”类的对象的列表。
如何正确加载文件?我需要哪些命令和“ using” .namespace?
我是否必须像在原始解决方案中那样定义新解决方案中的类?
“设备”类的定义如下:
[Serializable()]
public class Device
{
public string Name { get; set; }
public string Type { get; set; }
public int Station { get; set; }
public Function func{ get; set; }
[Serializable()]
public class Function
{
public string Name { get; set; }
public Function() { }
public Function(string name = "No Name")
{
Name = name;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
}
public Function(SerializationInfo info, StreamingContext context)
{
Name = (string)info.GetValue("Name", typeof(string));
}
}
public Device() { }
public Device(string name = "No Name", string type = "No type", int station = 0,
string sname="No Name", string sfeat="Nothing")
{
Name = name;
Type = type;
Station = station;
Func1= new Function(sname, sfeat);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
info.AddValue("Type", Type);
info.AddValue("Station", Station);
info.AddValue("Func1", Func1);
}
public Device(SerializationInfo info, StreamingContext context)
{
Name = (string)info.GetValue("Name", typeof(string));
Type = (string)info.GetValue("Type", typeof(string));
Station = (int)info.GetValue("Station", typeof(double));
Func1= (Function)info.GetValue("Func1", typeof(Function));
}
}
答案 0 :(得分:0)
您可以使用Xml.Serialization
这是最小的工作样本:
namespace ConsoleApp1
{
[Serializable]
public class Device
{
public string Name { get; set; }
public string Type { get; set; }
public int Station { get; set; }
public Function Function { get; set; }
}
[Serializable]
public class Function
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var file = "<some_path>";
using (var reader = new StreamReader(file))
{
var devices = (List<Device>)new XmlSerializer(typeof(List<Device>)).Deserialize(reader);
// do something with devices.
}
}
}
}