Serializing arraylist in C #

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

Is there a way to serialize a class using XmlSerializer?

Attempts still result in an error message:

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.

The following are some abbreviated class representations:

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; }
  }
}
+3
source share
5 answers

I had success with the following:

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

It leads to:

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

In your situation, I would try something like:

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

http://msdn.microsoft.com/en-us/library/2baksw0z(VS.85).aspx,

[XmlElement(Type = typeof(DataPoints))]
public ArrayList PolledData
+5

XmlSerializer . , .

ArrayList , XmlInclude , ArrayList.

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

List < > .

+3

, , (List < > ) ArrayList, , .

, ArrayList, , , .

, . [System.Xml.Serialization.XmlInclude(TypeOf (XMLSerialization.DataPoints))]

, XMLSerialization.DataPoints , ArrayList.

+1

, , , (, XmlInclude). , , , , . - , .

0

The method that I always used to serialize lists was to convert them to arrays (which have the necessary type information). I admit this is a little dirty, but if you cannot get the correct list for serialization, this will work.

0
source

Source: https://habr.com/ru/post/1705060/


All Articles