2013-02-12 100 views
3

時添加屬性我有這個類序列化到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> 

感謝

回答

1

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

+0

我仍然得到錯誤'有反映類型審計的錯誤' – plh 2013-02-12 17:43:21

+0

@plh你刪除了可空嗎??? – giammin 2013-02-12 17:59:36

+0

謝謝。就是這樣,我的ID是空的。 – plh 2013-02-12 19:12:47

0

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

否則,我不相信它可以序列可空類型