9

XmlElement有一个“Order”属性,在使用 XmlSerializer 进行序列化时,您可以使用它来指定属性的精确顺序(无论如何都相互关联)。

public class bookingList
{
    [XmlElement(Order = 1)]
    public string error { get; set; }
    [XmlElement(Order = 2)]
    public int counter { get; set; }
    [XmlElement(ElementName = "booking", Order = 3)]
    public List<booking> bookings = new List<booking>();
}

XmlAttribute有类似的东西吗?我只想设置属性的顺序,例如

<MyType end="bob" start="joe" />

<MyType start="joe" end="bob" />

这只是为了可读性,真的是我自己的利益。

4

5 回答 5

11

您不需要,因为属性在 XML 中没有顺序(XML 建议的第 3.1 节说:“请注意,开始标记或空元素标记中属性规范的顺序并不重要。”)。

于 2010-04-12T15:51:16.700 回答
10

根据我的经验,属性的序列化顺序与您定义公共属性的顺序相同。但是,如果您将属性与同一类中的字段组合在一起,例如

[Serializable()]
public class MyClass
{
   [XmlAttribute("ADoubleProp")]
   public double ADoubleProp { get; set; }

   [XmlAttribute("AnIntField")]
   public int AnIntField = 42;
}

然后字段首先被写入属性,然后是属性。上面的代码会产生类似这样的东西

<MyClass AnIntField="42" ADoubleProp="0" />
于 2014-09-23T00:25:07.190 回答
1

In C#, as far as what I have found, the order of attributes are serialized in the order that they are defined in the class.

See my answer to this question here: https://stackoverflow.com/a/21468092/607117

于 2014-01-30T21:50:11.410 回答
-1
xmlNode.Attributes.InsertAfter(newAttribute, refAttribute); 
xmlNode.Attributes.InsertBefore(newAttribute, refAttribute);
于 2020-12-11T14:25:54.167 回答
-1

如果您正在动态创建 XML,请尝试更改将属性附加到节点的顺序,它应该可以工作:)

于 2019-07-13T14:42:16.470 回答