简体   繁体   English

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

[英]XMLSerializer Deserialization - array element order

We are using XMLSerializer.Deserialize(XMLReader) on .Net 4.5 to deserialize XML into an Object Graph generated by xsd.exe. 我们在.Net 4.5上使用XMLSerializer.Deserialize(XMLReader)将XML反序列化为xsd.exe生成的对象图。

I would like to know what the expected deserialization behavior is for an array which is annotated with the XMLElementAttribute - specifically with regard to ordering. 我想知道用XMLElementAttribute注释的数组的预期反序列化行为是什么-特别是在排序方面。 For example: 例如:

For the following property: 对于以下属性:

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

And the following XML: 以及以下XML:

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

Will this always deserialize as ['One', 'Two', 'Three'] 这是否总是反序列化为['One','Two','Three']

So that the array order always matches the XML order 这样数组顺序始终与XML顺序匹配

Also is there any documentation I can reference that clearly states this. 另外,我可以参考任何文档来明确说明这一点。

Thanks 谢谢

Rob

Yes Its deserialize same order. 是的,它反序列化相同的顺序。 Check the code sample code and 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();


    }
}

You can find some awesome information about it on msdn which is provide by microsoft. 您可以在Microsoft提供的msdn上找到有关它的一些很棒的信息。

This is the "official" documentation 这是“官方”文档

The serialization is linear so you will alway get the same order normally. 序列化是线性的,因此您通常总是会获得相同的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM