简体   繁体   中英

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:xsd="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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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