XMLSerializer反序列化 - 数组元素顺序

时间:2014-08-25 00:44:45

标签: c# .net xml xml-serialization xmlserializer

我们正在使用.Net 4.5上的XMLSerializer.Deserialize(XMLReader)将XML反序列化为xsd.exe生成的对象图。

我想知道对于使用XMLElementAttribute注释的数组,预期的反序列化行为是什么 - 特别是关于排序。例如:

对于以下属性:

[System.Xml.Serialization.XmlElementAttribute("GivenName")]
  public string[] GivenName {
 // get() and set() methods
}

以下XML:

<root>
  <GivenName>One</GivenName>
  <GivenName>Two</GivenName>
  <GivenName>Three</GivenName>
</root>

这会一直反序列化为['One','Two','Three']

这样数组顺序总是与XML顺序匹配

还有我可以参考的任何文件清楚地说明了这一点。

由于

罗布

2 个答案:

答案 0 :(得分:0)

是反序列化相同的顺序。检查代码示例代码和输出:

Output

 [System.SerializableAttribute()]
public class SampleClass
{
    [System.Xml.Serialization.XmlElementAttribute(Order = 10)]
    public string Foo { get; set; }
    [System.Xml.Serialization.XmlElementAttribute(Order = 5)]
    public string Bar { get; set; }
    [System.Xml.Serialization.XmlElementAttribute("GivenName", Order = 15)]
    public string[] GivenNames { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        string[] names = new string[3] { "One", "Two", "Three" };

        SampleClass TestObj = new SampleClass { Bar = "dsdfsdf", Foo = "test", GivenNames = names };
        XmlSerializer SerializerObj = new XmlSerializer(typeof(SampleClass));
        // Create a new file stream to write the serialized object to a file
        TextWriter WriteFileStream = new StreamWriter(@"C:\files\test.xml");
        SerializerObj.Serialize(WriteFileStream, TestObj);
        // Cleanup
        WriteFileStream.Close();

        // Create a new file stream for reading the XML file
        FileStream ReadFileStream = new FileStream(@"C:\files\test.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

        // Load the object saved above by using the Deserialize function
        SampleClass LoadedObj = (SampleClass)SerializerObj.Deserialize(ReadFileStream);

        // Cleanup
        ReadFileStream.Close();


    }
}

答案 1 :(得分:-1)

你可以在微软提供的msdn上找到一些关于它的精彩信息。

This is the "official" documentation

序列化是线性的,因此您通常会获得相同的顺序。