views:

100

answers:

1

Is there a way to force XML elements generated from XML serialisation to be ordered in the same way as defined in the object class?

i.e.

class SerializableClass
{
    [XmlElement("Element.1")]
    public List<string> Element1
    { 
        get { return _Element1; }
        set { _Element1 = value; }   
    }
    private List<string> _Element1;
    [XmlElement("Element.2")]
    public int Element2;
    [XmlElement("Element.3")]
    public List<string> Element3
    { 
        get { return _Element3; }
        set { _Element3= value; }   
    }
    private List<string> _Element3;
    [XmlElement("Element.4")]
    public string Element4;
    [XmlElement("Element.5")]
    public bool Element5;
}

to

<Element.1>SomeValue 1</Element.1>
<Element.1>SomeValue 2</Element.1>
<Element.2>12</Element.2>
<Element.3>SomeValue 1</Element.3>
<Element.3>SomeValue 2</Element.3>
<Element.4>SomeString</Element.4>
<Element.5>true</Element.5>

I need the ordering to be exact because of an external validator.

+2  A: 

You should be able to set the Order on the serialization attribute:

public class SerializableClass
{
    [XmlElement("Element.1", Order = 1)]
    public List<string> Element1
    {
        get { return _Element1; }
        set { _Element1 = value; }
    }
    private List<string> _Element1;
    [XmlElement("Element.2", Order = 2)]
    public int Element2;
    [XmlElement("Element.3", Order = 3)]
    public List<string> Element3
    {
        get { return _Element3; }
        set { _Element3 = value; }
    }
    private List<string> _Element3;
    [XmlElement("Element.4", Order = 4)]
    public string Element4;
    [XmlElement("Element.5", Order = 5)]
    public bool Element5;
}
Marc Gravell
Thanks Marc, much appreciated. I also found out that making all members properties rather than mixing them also seemed to have the desired effect.
Nat Ryall