3

I have a field:

public Field[][] fields;

And I want an 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 do I achieve this?


Well, actually I don't need to stick to an array of arrays. The fields do represent a 2D space, so it was a natural choice. Would a Dictionary serialize the way I need?

2
  • could you tell us where this x and y attributes are populated. you could transform your xml using xslt transform Commented Mar 31, 2012 at 16:23
  • I didnt give all the details, x and y are public fields of Field class and are mapped to the attributes. The Field class serializes okay. I just cant find a way to serialize a 2d array, neither multi-dim, array of arrays nor jagged. Commented Mar 31, 2012 at 16:29

2 Answers 2

3

You can create a property that converts between the 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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I thought about this, but how would you deserialize it ..?
See my updated answer. It assumes several things: the x and y properties match the array indexes; there may be gaps in x; for a given x, there are no gaps in y (that is, if Fields[9][3] exists, so do Fields[9][0], Fields[9][1], and Fields[9][2]); it is OK to drop unused elements at the end of each array.
1

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

You can then specify in your WriteXml() method how the xml should be written (formatted).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.