我在C#
中进行XML
反序列化时遇到问题。我有以下XML
:
<?xml version="1.0" encoding="utf-8"?>
<head>
<person>
<name>Jim Bob</name>
<dateOfBirth>1990-01-01</dateOfBirth>
</person>
<policy>
<number>1</number>
<pet>
<name>Snuffles</name>
<dateOfBirth>2000-01-01</dateOfBirth>
</pet>
</policy>
</head>
有了这个,我试图将其映射到以下类:
public class head
{
public policy policy { get; set; }
public person person { get; set; }
}
public class person
{
public string name { get; set; }
public DateTime dateOfBirth { get; set; }
[XmlElement("policy")]
public List<policy> policy { get; set; }
}
public class policy
{
public string number { get; set; }
[XmlElement("pet")]
public List<pet> pet { get; set; }
}
public class pet
{
public string name { get; set; }
[XmlElement("dateOfBirth")]
public DateTime dateOfBirth { get; set; } //<~~ Issue is with this property
}
问题是pet
类中的dateOfBirth
属性在反序列化时没有被填充,我不知道为什么。这是因为与person
类中的dateOfBirth
属性存在命名冲突吗?
尝试以下使用ParseExact的代码。如果你仍然遇到问题,你可能必须处理DateTime为空的情况:
public class pet
{
public string name { get; set; }
private DateTime _dateOfBirth { get; set; } //<~~ Issue is with this property
[XmlElement("dateOfBirth")]
public string DateOfBirth
{
get { return _dateOfBirth.ToString("yyyy-MM-dd"); }
set { _dateOfBirth = DateTime.ParseExact(value, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); }
}
}
我通过使用dateOfBirth
字段上的[XmlElementAttribute(DataType = "date")]
属性解决了这个问题。修改后的类看起来是这样的:
public class pet
{
public string name { get; set; }
[XmlElementAttribute(DataType = "date")]
public DateTime dateOfBirth { get; set; }
}