我有一个小问题 - XML 反序列化完全忽略了不按字母顺序排列的项目。在示例对象中(问题末尾的描述),Birthday
节点位于 FirstName
节点之后,反序列化后将被忽略并分配默认值。对于任何其他类型和名称也是如此(我在 PatientInfo
类型的节点 Patient
之后有 Guid
类型的节点 CaseId
,反序列化后它有默认值)。
我正在一个应用程序中使用下一个代码对其进行序列化:
public static string SerializeToString(object data)
{
if (data == null) return null;
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
// what should the XmlWriter do?
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
NewLineChars = ""
};
using (var stringwriter = new System.IO.StringWriter())
{
// Use an XmlWriter to wrap the StringWriter
using (var xmlWriter = XmlWriter.Create(stringwriter, settings))
{
var serializer = new XmlSerializer(data.GetType(), "");
// serialize to the XmlWriter instance
serializer.Serialize(xmlWriter, data, ns);
return stringwriter.ToString();
}
}
}
这种方法用于获得正确的结果作为 WebMethod 的参数(完整问题描述 here )。结果是这样的:
<PatientInfo><FirstName>Foo</FirstName><Birthday>2015-12-19T16:21:48.4009949+01:00</Birthday><RequestedClientID>00000000-0000-0000-0000-000000000000</RequestedClientID>00000000-0000-0000-0000-000000000000</patientId></PatientInfo>
我还以简单的方式在另一个应用程序中反序列化它
public static T Deserialize<T>(string xmlText)
{
if (String.IsNullOrEmpty(xmlText)) return default(T);
using (var stringReader = new StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
}
示例对象:
[XmlRoot("PatientInfo")]
public class PatientInfo
{
[XmlElement("FirstName")]
public string FirstName { get; set; }
[XmlElement("LastName")]
public string LastName { get; set; }
[XmlElement("SSN")]
public string SSN { get; set; }
[XmlElement("Birthday")]
public DateTime? Birthday { get; set; }
[XmlElement("RequestedClientID")]
public Guid RequestedClientID { get; set; }
[XmlElement("patientId")]
public Guid patientId { get; set; }
}
所以,我想回答以下两个问题之一 - 1)如何调整序列化以使所有项目按字母顺序排列? 2)如何调整我的反序列化,这样它就不会忽略不按字母顺序排列的项目?
感谢任何帮助。
更新:
刚刚发现,我正在使用的反序列化方法实际上在我的问题中根本没有使用,因为我使用 WebMethod 的序列化信息作为数据,并且它是通过 WCF 的某些内部机制进行反序列化的。
最佳答案
WCF uses DataContractSerializer
。此序列化程序对 XML 元素顺序敏感,请参阅 Data Member Order 。没有快速的方法来 disable this ,您需要将序列化器替换为 XmlSerializer
。
要执行此操作,请参阅 Using the XmlSerializer Class ,然后应用[XmlSerializerFormat]
到您的服务,例如:
[ServiceContract]
[XmlSerializerFormat]
public interface IPatientInfoService
{
[OperationContract]
public void ProcessPatientInfo(PatientInfo patient)
{
// Code not shown.
}
}
[XmlRoot("PatientInfo")]
public class PatientInfo
{
[XmlElement("FirstName")]
public string FirstName { get; set; }
[XmlElement("LastName")]
public string LastName { get; set; }
[XmlElement("SSN")]
public string SSN { get; set; }
[XmlElement("Birthday")]
public DateTime? Birthday { get; set; }
[XmlElement("RequestedClientID")]
public Guid RequestedClientID { get; set; }
[XmlElement("patientId")]
public Guid patientId { get; set; }
}
关于c# - XML 反序列化忽略不按字母顺序排列的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773293/