[英]Adding attributes when serializing to XML
I have this class 我有这门课
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; }
}
When I serialize it looks like this 当我序列化它看起来像这样
<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>
I added this class to try get the id fields as attribute 我添加了这个类来尝试将id字段作为属性
public class ValueWithId
{
[XmlAttribute ("id")]
public long? Id { get; set; }
[XmlText] // Also tried with [XmlElement]
public string Description { get; set; }
}
Rewrote my class to this 重写了我的课程
[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; }
}
But I get the error 'There was an error reflecting type Audit' 但我收到错误'有一个错误反映类型审计'
I am trying to get the following as the XML 我试图将以下内容作为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>
Thanks 谢谢
Add Serializable
attribute to class ValueWithId
将
Serializable
属性添加到类ValueWithId
[Serializable]
public class ValueWithId
{
[XmlAttribute ("id")]
public long Id { get; set; }
[XmlText]
public string Description { get; set; }
}
and if you look at your exception you'll find it quite eloquent: 如果你看看你的异常,你会发现它很有说服力:
"Cannot serialize member 'Id' of type System.Nullable`1[System.Int64]. XmlAttribute/XmlText cannot be used to encode complex types."}
“无法序列化System.Nullable`1 [System.Int64]类型的成员'Id'.XmlAttribute / XmlText不能用于编码复杂类型。”}
if you need to serialize a nullable look there: Serialize a nullable int 如果你需要序列化一个可空的外观: 序列化一个可空的int
I agree with giammin's answer, and it works. 我同意giammin的回答,并且它有效。 If you want to leave the id nullable, then I would suggest just removing the attribute above Id.
如果你想让id可以为空,那么我建议只删除Id上面的属性。 You'll get an output simiar to this":
你会得到一个输出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>
Otherwise, I don't believe it can serialize nullable types 否则,我不相信它可以序列化可空类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.