序列化为XML时添加属性

时间:2013-02-12 17:23:15

标签: c# xml xml-serialization

我有这个班级

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>

谢谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我同意giammin的回答,并且它有效。如果你想让id可以为空,那么我建议只删除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>

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