1

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.

kmort
  • 2,848
  • 2
  • 32
  • 54
  • 1
    Not answering your actual question but your could force the order using `[XmlElement(Order=1)]` ... – Filburt Jan 08 '14 at 21:46

1 Answers1

1

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
Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184