反序列化xml,包括名称空间 [英] Deserializing xml, including namespace
问题描述
我正在尝试反序列化某些XML,但无法使名称空间/ xsi:type ="Model"
正常工作.如果将 xsi:type ="Model"
排除在XML之外,它将起作用,但必须存在.如果将名称空间放在模型之外,则会出现错误,如果将其重命名,则会得到一个空列表.
I am trying to deserialize some XML and I can't get the namespace / xsi:type="Model"
to work. If xsi:type="Model"
is left out of the XML it works, but it has to be there. If I leave the namespace out of my Model, I get an error, if I rename it, I get an empty list.
XML
<Vehicles xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Vehicle xsi:type="Model">
<Id>238614402</Id>
</Vehicle>
<Vehicle xsi:type="Model">
<Id>238614805</Id>
</Vehicle>
</Vehicles>
模型
[XmlRootAttribute("Vehicles")]
public class Vehicles
{
public Vehicles()
{
Vehicle = new List<Vehicle>();
}
[XmlElement(ElementName = "Vehicle", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public List<Vehicle> Vehicle { get; set; }
}
public class Vehicle
{
[XmlElement("Id")]
public int Id { get; set; }
}
反序列化
XmlSerializer serializer = new XmlSerializer(typeof(Vehicles));
string carXML = "<Vehicles xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Vehicle xsi:type=\"Model\"> <Id>238614402</Id> </Vehicle><Vehicle xsi:type=\"Model\"> <Id>238614805</Id> </Vehicle></Vehicles>";
var cars = (Vehicles)serializer.Deserialize(new StringReader(carXML));
上面的示例返回一个空列表,因为据我所知,命名空间是错误的-如何获取它以返回实际列表?
The example above returns an empty list, because the namespace is wrong, as far as I know - how do I get it to return an actual list?
编辑我对XML没有任何控制权,我是从其他提供商那里获得的,所以我将不得不相应地更改其余代码.
EDIT I don't have any control over the XML, I'm getting that from a different provider, so I will have to change the rest of the code accordingly.
推荐答案
请尝试以下操作:
public partial class Vehicles
{
[XmlElement("Vehicle")]
public Vehicle[] Vehicle { get; set; }
}
[XmlInclude(typeof(Model))]
public partial class Vehicle
{
public uint Id { get; set; }
}
public class Model : Vehicle { }
请注意输入车辆
.
var xs = new XmlSerializer(typeof(Vehicles));
Vehicles vehicles;
using (var fs = new FileStream("file.xml", FileMode.Open))
{
vehicles = (Vehicles)xs.Deserialize(fs);
}
foreach (var vehicle in vehicles.Vehicle)
{
Console.WriteLine(vehicle.GetType()); // Model
Console.WriteLine(vehicle.Id);
}
无需指定名称空间.序列化属性时,会自动添加实际类型为 Model
的属性 xsi
.
No need to specify namespace. When serializing an attribute xsi
will be added automatically with actual type Model
.
xs.Serialize(Console.Out, vehicles);
这篇关于反序列化xml,包括名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!