Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing an arraylist in C#

Tags:

c#

I have a class that contains a number of standard fields and an arraylist.

Is there any way to serialize the class using an XmlSerializer?

Attempts so far result in an error message saying:

Unhandled Exception: System.InvalidOperationException: There was an error
generating the XML document. ---> System.InvalidOperationException: The type
XMLSerialization.DataPoints was not  expected. Use  the XmlInclude or
SoapInclude attribute  to specify types that are not known statically.

Some cut-down representations of the classes are shown below:

public class StationData
{
  private DateTime _CollectionDate;
  private string _StationID;
  private ArrayList _PolledData;

  public StationData()
  {
  }
  public DateTime CollectionDate
  {
    get { return _CollectionDate; }
    set { _CollectionDate = value; }
  }
  public string StationID
  {
    get { return _StationID; }
    set { _StationID = value; }
  }
  [XmlInclude(typeof(DataPoints))]
  public ArrayList PolledData
  {
    get { return _PolledData; }
    set { _PolledData = value; }
  }
}

public class DataPoints
{
  private string _SubStationID;
  private int _PointValue;

  public DataPoints
  {
  }
  public string SubStationID
  {
    get { return _SubStationID; }
    set { _SubStationID = value; }
  }
  public int PointValue
  {
    get { return _PointValue; }
    set { _PointValue = value; }
  }
}
like image 970
phrenetic Avatar asked Dec 06 '25 05:12

phrenetic


2 Answers

I have had success with the following:

[XmlArray("HasTypeSpecialisations")]
[XmlArrayItem("TypeObject", typeof(TypeObject), IsNullable = false)]
public List<TypeObject> TypeSpecialisations

This results in:

<HasTypeSpecialisations>
    <TypeObject />
    <TypeObject />
</HasTypeSpecialisations>

In your situation I would try something like:

[XmlArrayItem(typeof(DataPoints))]
public ArrayList PolledData

Based on this link http://msdn.microsoft.com/en-us/library/2baksw0z(VS.85).aspx you should also be able to use this

[XmlElement(Type = typeof(DataPoints))]
public ArrayList PolledData
like image 126
toad Avatar answered Dec 07 '25 17:12

toad


The XmlSerializer generates some code at runtime to serialize your class. It is necessary for this class to know all types that can occur.

The ArrayList does not give this information, but you can give it by using a XmlInclude attribute on the property that returns the ArrayList.

[XmlInclude(typeof(DataPoints))]
public ArrayList Points {
   ...
}

You could also use the generic List<> class.

like image 26
GvS Avatar answered Dec 07 '25 18:12

GvS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!