1

I have the following class.

public class SerialisableClass
{

    [XmlElement(ElementName ="title")]
    public string Title { get; set; }

    [XmlElement(ElementName = "repCycle")]
    public RepCycle RepCycle { get; set; } 
}

public class RepCycle
{
    [XmlElement(ElementName = "data")]
    public List<Data> Data { get; set; }

    [XmlElement(ElementName = "type")]
    public int Type { get; set; }
}

public class Data
{
    [XmlArray("data")]
    [XmlArrayItem(ElementName = "item")]
    public List<int> Items { get; set; }
}

If I serialise this...

        using (var writer = new StreamWriter(_filename))
        {
            XmlSerializer serialiser = new XmlSerializer(typeof(SerialisableClass));
            serialiser.Serialize(writer, myObject);
            writer.Flush();
        }

it gives me the following output:

<?xml version="1.0" encoding="utf-8"?>
<SerialisableClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <title>Hello, World</title>
  <repCycle>
    <data>
      <data>
        <item>25</item>
        <item>23</item>
        <item>15</item>
      </data>
    </data>
    <data>
      <data>
        <item>1</item>
        <item>2</item>
        <item>3</item>
      </data>
    </data>
    <type>0</type>
  </repCycle>
</SerialisableClass>

But that is one <data> level too many. What I want is something more like...

  <repCycle>
    <data>
      <item>25</item>
      <item>23</item>
      <item>15</item>
    </data>

...etc.

How can I achieve this? I can't remove the RepCycle class (and just store it as a List<Data>) because then I won't be able to have the Type element. Also, I have tried making Data just a List<List<int>> but then I get the errors...

error CS0030: Cannot convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List'

error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List>'

I have read that multidimensional arrays are not supported by the serialisation, so I assume the same goes for multidimensional lists.

komodosp
  • 3,316
  • 2
  • 30
  • 59
  • 2
    [XmlArray("data")] and [XmlArrayItem(ElementName = "item")] are adding the extra layer of tags. Use [XmlElement] instead. – jdweng Sep 05 '18 at 11:09
  • @jdweng - Thanks a million - thought I needed the XmlArray to call the items `` but [XmlElement(ElementName="item") did the same thing, if you make that an answer I'll accept it... – komodosp Sep 05 '18 at 11:16

0 Answers0