net xmlserializer : keeping attributes order

泪湿孤枕 提交于 2019-12-25 05:22:13

问题


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?


回答1:


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."




回答2:


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



来源:https://stackoverflow.com/questions/11452293/net-xmlserializer-keeping-attributes-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!