问题描述
我有一个名为VehicleInfo的XML文件。
我想反序列化Vehicle List中的VehicleInfo。
现在,我有一个名为Vehicle的基类,以及三个名为Car,Bike和Truck的派生类。
如何基于xml中Vehicle节点的值反序列化车辆的特定对象。
(例如,如果节点值为Car,则应将汽车对象存储在车辆列表中)
I have one XML file called VehicleInfo.I want to deserialize VehicleInfo in List of Vehicle.Now I have one base class called Vehicle and three derived class named as Car, Bike, Truck.How to deserialize specific object of vehicle based on value of Vehicle node in xml.(ex. if node value is Car than object of car should be stored in List of vehicle)
<Vehicles>
<Vehicle>Car</Vehicle>
<Vehicle>Bike</Vehicle>
<Vehicle>Truck</Vehicle>
</Vehicles>
例如,
VehicleList类:
VehicleList class :
public class VehicleList
{
List<Vehicle> lstVehicles = new List<Vehicle>();
}
车辆类别:
public class Vehicle
{
public string name = "Vehicle";
}
汽车等级:
public class Car : Vehicle
{
public Car()
{
name = "Car";
}
}
自行车等级:
public class Bike : Vehicle
{
public Bike()
{
name = "Bike";
}
}
卡车类别:
public class Truck : Vehicle
{
public Truck()
{
name = "Truck";
}
}
这个Vehicle程序只是示例,
This Vehicle program is just example,
因此,如何根据节点Vehicle的值反序列化VehicleList类中的Vehicle List中的特定对象(例如,汽车,自行车或卡车)。
So, How can I deserialize specific object (Such as Car, Bike, or Truck) in List of Vehicle in VehicleList class based on value of node Vehicle.
推荐答案
以下是要序列化的代码和结果。 XML不能将数组作为根元素。因此,在这种情况下,有两类是有意义的:车辆和车辆。参见以下代码:
Here is code and results to serialize. XML you cannot have an array as a root element. So in this case it make sense to have two classes : Vehicles and Vehicle. See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication107
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Vehicles vehicles = new Vehicles()
{
vehicles = new List<Vehicle>() {
new Car() { make = "BMW"},
new Bike() { make = "Buffalo"},
new Truck() { make = "MAC"}
}
};
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME, settings);
XmlSerializer serializer = new XmlSerializer(typeof(Vehicles));
serializer.Serialize(writer, vehicles);
}
}
public class Vehicles
{
[XmlElement("Vehicle")]
public List<Vehicle> vehicles { get; set; }
}
[XmlInclude(typeof(Car))]
[XmlInclude(typeof(Bike))]
[XmlInclude(typeof(Truck))]
public class Vehicle
{
public string make { get; set; }
}
public class Car : Vehicle
{
}
public class Bike : Vehicle
{
}
public class Truck : Vehicle
{
}
}
以下是结果:
<?xml version="1.0" encoding="utf-8"?>
<Vehicles xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Vehicle xsi:type="Car">
<make>BMW</make>
</Vehicle>
<Vehicle xsi:type="Bike">
<make>Buffalo</make>
</Vehicle>
<Vehicle xsi:type="Truck">
<make>MAC</make>
</Vehicle>
</Vehicles>
这篇关于如何基于xml节点的值将子对象反序列化为父列表(例如,List< Parent>)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!