[英]Why System.Xml.Serialization output order changes
我刚刚在C#中获得了XML序列化。 在弄清楚它的过程中,我偶然发现了一个奇怪的地方,想知道为什么。
如果我使用以下代码,
[Serializable, XmlRoot("ThisIsTheRootName")]
public class Person
{
public string FirstName;
public string MiddleName;
public string LastName;
[XmlText]
public string Text;
}
序列化时得到以下输出:
<?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>
所有元素都按我预期的顺序排列。
如果我改用属性而不是字段,则顺序突然不是我期望的。 码:
[Serializable, XmlRoot("ThisIsTheRootName")]
public class Person
{
public string FirstName;
public string MiddleName { get; set; }
public string LastName;
[XmlText]
public string Text;
}
输出:
<?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>
为什么订单会更改? 我应该为此选择属性或字段吗? 有关系吗?
在Windows 7 64bit上使用Visual Studio 2010,C#、. NET 4.0框架。
因为默认情况下, XmlSerializer
先对字段进行序列化,然后对属性进行序列化。 但是,可以使用XmlElement
属性及其Order
属性来更改此行为,如下所示:
[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;
}
另外,您可能想看看这些问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.