强制XML元素在序列化时匹配类顺序

时间:2009-09-08 13:39:36

标签: xml serialization xml-serialization

有没有办法强制从XML序列化生成的XML元素以与对象类中定义的相同方式排序?

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;
}

<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>

由于外部验证器,我需要准确的订购。

1 个答案:

答案 0 :(得分:4)

您应该能够在序列化属性上设置Order

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;
}