我正在尝试创建这样的 xml:
<CreditApplication>
<ApplicantData>
<FirstName> John </FirstName>
<LastName> Smith </LastName>
</ApplicantData>
<CoApplicantData>
<FirstName> Mary </FirstName>
<LastName> Jane </LastName>
</CoApplicantData>
</CreditApplication>
我已经这样定义了我的类:
[XmlRoot("CreditApplication")]
public class CreditApplication
{
[XmlElement("ApplicantData")]
public CreditApplicant Applicant;
[XmlElement("CoApplicantData")]
public CreditApplicant CoApplicant;
}
public class CreditApplicant : INotifyPropertyChanged
{
...
[XmlElement("FirstName")]
public string FirstName { set; get; }
[XmlElement("LastName")]
public string LastName { set; get; }
...
}
在 CreditApplication 类中,我引用了在程序中其他地方定义的枚举,这些枚举也需要可序列化。
当我实际运行程序并尝试使用以下方法对类进行序列化时:
XmlSerializer applicantXMLSerializer = new XmlSerializer(typeof(CreditApplication));
StringWriter applicantStringWriter = new StringWriter();
XmlWriter applicantXmlWriter = XmlWriter.Create(applicantStringWriter);
applicantXMLSerializer.Serialize(applicantXmlWriter, application);
var applicantXML = applicantStringWriter.ToString();
但我收到错误:There was an error reflecting type 'Models.Credit.CreditApplication'
有人知道我做错了什么吗?
编辑:
我已更新上述代码以反射(reflect)建议的更改。不过,还存在其他问题。
我有一个这样定义的枚举:
[DataContract]
public enum Relationship
{
Spouse = 4,
ResidesWith = 1,
Parent = 2,
Other = 3,
PersonalGuarantor = 5,
CoApplicant = 6
}
如上所示,零不是一个已定义的选项。因此,没有默认值。我围绕未设置的关系默认为零的想法设计了该程序。这样我就可以轻松查看是否已设置值。如果我定义了零,然后将其初始化为“无关系”或类似的内容,则无法判断用户是否将值设置为“无关系”,或者他们是否只是没有选择选项。
罢工>
移动:
最佳答案
您想要使用XMLElement Attribute而不是 XMLAttribute Attribute如果您的字段应该是 XML 中的单独元素。
例如:
<SimpleXML name="test">
<child>SomeValue</child>
</SimpleXML>
name
是一个属性,而 child
是一个元素。
关于c# - Xml 类序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985482/