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>
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.
Vehicle
element in your example isn'thttp://www.w3.org/2001/XMLSchema-instance
- that namespace, within theVehicles
element of your xml, has been associated with thexsd
namespace prefix - but no such prefix has been applied to theVehicle
elements within. Therefore, it's in the global namespace instead. – Heterothallic