Deserializing xml into an ArrayList of objects in C#
The following xml is a result of serializing an ArrayList of Asset objets
<ArrayOfAsset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:开发者_如何学Cxsd="http://www.w3.org/2001/XMLSchema">
<Asset>
<name>bill</name>
<type>perosn</type>
</Asset>
<Asset>
<name>bill</name>
<type>perosn</type>
</Asset>
</ArrayOfAsset>
I can deserialize this with the default C# deserializer no problem. If my root element changes from ArrayOfAsset to assets, my deserializer blows up. How can I make my deserializer aware of this change.
Here is my deserialization code:
StreamReader sr = new StreamReader("c:\\assest.xml");
string r = sr.ReadToEnd();
List<Asset> list;
Type[] extraTypes = new Type[1];
extraTypes[0] = typeof(Asset);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Asset>), extraTypes);
object obj = serializer.Deserialize(xReader);
list = (List<Asset>)obj;
I'm having the same problem.
In the MSDN documentation is specified:
Note The XmlSerializer cannot deserialize the following: arrays of ArrayList and arrays of List.
But I don't really know if that means that you cannot deserialize arrays of ArrayList or ArrayList... it is not clear for me.
http://msdn.microsoft.com/en-us/library/dk9cbaf1%28v=vs.110%29.aspx
Use Service Stack serializer :)
As soon as you use "default" serialization, you can't change XML format. To support tweaked XML, you have to provide some metadata that overrides default serialization. For example: https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlarray(v=vs.110).aspx
Also it could be worth to attach attributes to your Asset class (and related). That way you can describe [XmlArray] and [XmlArrayItem] to support required tags/subtags https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute(v=vs.110).aspx
精彩评论