Serialize an array of arrays as a single XML element

I have a field:

public Field[][] fields;

      

And I want XML:

<Fields>
    <Field x="0" y="0">
       ...
    </Field>
    <Field x="0" y="1">
       ...
    </Field>
    ...
</Fields>

      

Unfortunately C # XmlSerializer gives me

<Fields>
    <ArrayOfField>
        .... some fields here
    </ArrayOfField>
    <ArrayOfField>
       .... some here
    </ArrayOfField>
            ...
</Fields>

      

How can I achieve this?


Well, actually I don't have to stick with an array of arrays. The fields are really 2D space, so this was a natural choice. Will Dictionary

serialize what I need?

+3


source to share


2 answers


You can create a property that converts an array of arrays and a single array:



using System.Linq;

...

[XmlIgnore]
public Field[][] Fields;

[XmlArray("Fields")]
public Field[] SerializedFields
{
    get
    {
        return this.Fields.SelectMany(fields => fields).ToArray();
    }
    set
    {
        this.Fields = new Field[value.Max(field => field.x) + 1][];
        for (int x = 0; x < this.Fields.Length; x++)
        {
            this.Fields[x] = value.Where(field => field.x == x).ToArray();
        }
    }
}

      

+2


source


I think you need to implement the IXmlSerializable interface: http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx



Then you can specify in your method WriteXml()

how the XML file should be written (formatted).

+1


source







All Articles