简体   繁体   English

反序列化xml,包括命名空间

[英]Deserializing xml, including namespace

I am trying to deserialize some XML and I can't get the namespace / xsi:type="Model" to work. 我试图反序列化一些XML,我无法使命名空间/ xsi:type="Model"工作。 If xsi:type="Model" is left out of the XML it works, but it has to be there. 如果xsi:type="Model"被排除在XML之外,那么它必须存在。 If I leave the namespace out of my Model, I get an error, if I rename it, I get an empty list. 如果我将命名空间从模型中删除,我会收到错误,如果我重命名它,我会得到一个空列表。

XML 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>

Model 模型

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

}

Deserializing 反序列化

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? 上面的例子返回一个空列表,因为命名空间是错误的,据我所知 - 如何让它返回实际列表?

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. 编辑我没有对XML的任何控制,我从不同的提供程序获得,所以我将不得不相应地更改其余的代码。

Please try this: 请试试这个:

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 { }

Pay attention to type vehicle . 注意打字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);
}

No need to specify namespace. 无需指定命名空间。 When serializing an attribute xsi will be added automatically with actual type Model . 序列化属性时,将使用实际类型Model自动添加属性xsi

xs.Serialize(Console.Out, vehicles);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM