kmort
kmort

Reputation: 2948

Why System.Xml.Serialization output order changes

I just picked up XML serialization in C#. In the course of figuring it out, I stumbled upon an oddity and wanted to know why.

If I use the following code,

[Serializable, XmlRoot("ThisIsTheRootName")]
public class Person
{
  public string FirstName;
  public string MiddleName;
  public string LastName;
  [XmlText]
  public string Text;
}

I get this output when I serialize:

    <?xml version="1.0" encoding="IBM437"?>
<ThisIsTheRootName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>firstname</FirstName>
  <MiddleName>middlename</MiddleName>
  <LastName>lastname</LastName>This is some text</ThisIsTheRootName>

All the elements are in the order I expected.

If I switch to using a property instead of a field, suddenly the order is not what I would expect. Code:

[Serializable, XmlRoot("ThisIsTheRootName")]
public class Person
{
  public string FirstName;
  public string MiddleName { get; set; }
  public string LastName;
  [XmlText]
  public string Text;
}

Output:

<?xml version="1.0" encoding="IBM437"?>
<ThisIsTheRootName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>firstname</FirstName>
  <LastName>lastname</LastName>This is some text<MiddleName>middlename</MiddleName></ThisIsTheRootName>


Why does the order change? Should I prefer properties or fields for this? Does it matter?

Using Visual Studio 2010, C#, .NET 4.0 framework on Windows 7 64bit.

Upvotes: 1

Views: 858

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101711

Because by default XmlSerializer serialize your fields first then your properties. However, you can change this behavior with using XmlElement attribute and it's Order property like this:

[Serializable, XmlRoot("ThisIsTheRootName")]
public class Person
{
  [XmlElement(Order = 1)]
  public string FirstName;
  [XmlElement(Order = 2)]
  public string MiddleName { get; set; }
  [XmlElement(Order = 3)]
  public string LastName;
  [XmlText]
  public string Text;
}

Also you might want take a look at these questions:

  1. .NET Serialization Ordering
  2. Force XML elements to match the class order when serializing
  3. Change the order of elements when serializing XML

Upvotes: 1

Related Questions