序列化到XML
问题描述:
时添加属性我有这个类序列化到XML
public class Audit
{
public string name { get; set;}
public DateTime AuditDate { get; set;}
public long? DepartmentId {get; set;}
public string Department { get; set;}
public long? StateId { get; set;}
public string? State { get; set; }
public long? CountryId { get; set; }
public string Country { get; set; }
}
当我序列,它看起来像这样
<Audit>
<name>George</name>
<AuditDate>01/23/2013</AuditDate>
<DepartmentId>10</DepartmentId>
<Department>Lost and Found</Department>
<StateId>15</StateId>
<State>New Mexico</StateId>
<CountryId>34</CountryId>
<Country>USA</Country>
</Audit>
我加入这个类来尝试获得ID字段属性
public class ValueWithId
{
[XmlAttribute ("id")]
public long? Id { get; set; }
[XmlText] // Also tried with [XmlElement]
public string Description { get; set; }
}
将我的课程改写为此
[Serializable]
public class Audit
{
public string name { get; set;}
public DateTime AuditDate { get; set;}
public ValueWithId Department { get; set;}
public ValueWithId State { get; set; }
public ValueWithId Country { get; set; }
}
但我得到的错误“有反射式审计的错误”
我试图让下面的XML
<Audit>
<name>George</name>
<AuditDate>01/23/2013</AuditDate>
<Department id=10>Lost and Found</Department>
<State id=15>New Mexico</State>
<Country id=34>USA</Country>
</Audit>
感谢
答
添加Serializable
属性类ValueWithId
[Serializable]
public class ValueWithId
{
[XmlAttribute ("id")]
public long Id { get; set; }
[XmlText]
public string Description { get; set; }
}
如果y ou看看你的例外,你会发现它相当雄辩:
“无法序列化System.Nullable`1 [System.Int64]类型的成员'Id'。 XmlAttribute/XMLTEXT不能用于编码复杂类型“}
,如果你需要序列可为空在那里寻找: Serialize a nullable int
答
我giammin的答案达成一致,和它的作品如果你想。离开ID为空,那么我建议只删除上面标识的属性,您会得到一个输出simiar这种“:
<Audit xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>George</name>
<AuditDate>2013-01-23T00:00:00</AuditDate>
<Department>
<Id>10</Id>Lost and Found</Department>
<State>
<Id>15</Id>New Mexico</State>
<Country>
<Id>34</Id>USA</Country>
</Audit>
否则,我不相信它可以序列可空类型
我仍然得到错误'有反映类型审计的错误' – plh 2013-02-12 17:43:21
@plh你删除了可空吗??? – giammin 2013-02-12 17:59:36
谢谢。就是这样,我的ID是空的。 – plh 2013-02-12 19:12:47