0

I can sucessfully able to write my class Item in a xml file. But the orders of atttributes change...

Suppose I have Item class

class Item
{
   Name
   Price
   Id

}

when I write it to xml file using .net xmlserializer I get different order from my class decleration such as

<Item Price="y" Name="x"  Id="z"  />

But I want it like this [ keep decleration order]

<Item Name="x" Price="y" Id="z"  />

How can İ do it in NET?

Novalis
  • 2,265
  • 6
  • 39
  • 63
  • 5
    This might be a dumb question, but since this is xml and you should be parsing it with an xml library.... why does it matter? – asawyer Jul 12 '12 at 12:54
  • 1
    I do not depend on order guys...I just want some cosmetic good looking on my xml...And I know that XML is not for human reading...But i am mad about "form" and I want it in some order... – Novalis Jul 12 '12 at 13:09

2 Answers2

2

You shouldn't be concerend with the order. If you are, then you are not processing your xml properly

section 3.1 "Note that the order of attribute specifications in a start-tag or empty-element tag is not significant."

saj
  • 4,626
  • 2
  • 26
  • 25
  • I know that XML is not for human reading...It may be stupid but I want the order just because of some "cosmetic" good looking...That is all... – Novalis Jul 12 '12 at 13:07
  • I personally wouldn't bother, like you said it's not for human reading. But if you really want to I think this article may deal with something similar http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-object-xml-serialization-with-net-xml-attributes.aspx – saj Jul 12 '12 at 13:18
0

You you are keen on the order of the attributes, then the IXmlSerializable interface will give you control of the serialization/deserialization process of the class. The order of attributes is determined by the order of the lines of code:

public void WriteXml(XmlWriter writer)
{
  //First example xml element
  writer.WriteStartElement("Item1");
  writer.WriteAttributeString("Name", Name);
  writer.WriteAttributeString("Price", Price);
  writer.WriteAttributeString("Id", Id);
  writer.WriteEndElement();

  //Second example xml element
  writer.WriteStartElement("Item2");
  writer.WriteAttributeString("Price", Price);
  writer.WriteAttributeString("Id", Id);
  writer.WriteAttributeString("Name", Name);
  writer.WriteEndElement();
}

outputs:

<Item1 Name="x" Price="y" Id="z">
<Item2 Price="y" Id="z" Name="x">

As you see, if you switch around lines of code, then the order is changed.

But beware, implementing this interface overwrites the default process, letting it be up to you to write the entire serialization/deserialization process.

Regards Nautious

Anders
  • 1,590
  • 1
  • 20
  • 37