3

我有这门课

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>

谢谢

4

2 回答 2

1

为类添加Serializable属性ValueWithId

[Serializable]
public class ValueWithId
{
   [XmlAttribute ("id")]
   public long Id { get; set; }

   [XmlText] 
   public string Description { get; set; }
}

如果您查看您的异常,您会发现它很有说服力:

“无法序列化 System.Nullable`1[System.Int64] 类型的成员 'Id'。XmlAttribute/XmlText 不能用于编码复杂类型。”}

如果您需要在此处序列化可为空的外观: Serialize a nullable int

于 2013-02-12T17:29:31.627 回答
0

我同意 giammin 的回答,并且有效。如果您想让 id 可以为空,那么我建议您只删除 Id 上方的属性。您将获得与此类似的输出”:

<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>

否则,我不相信它可以序列化可空类型

于 2013-02-12T18:05:46.157 回答