gpt4 book ai didi

c# - Xml 类序列化错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:06 25 4
gpt4 key购买 nike

我正在尝试创建这样的 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
}

如上所示,零不是定义的选项。因此,没有默认值。我围绕未设置默认为零的关系的想法设计了程序。这样我就可以轻松查看是否已设置值。如果我定义了零,然后将其初始化为“无关系”或类似的东西,那么就无法判断用户是否将该值设置为“无关系”,或者他们是否根本没有选择一个选项。

移动:

XML Serialization of Enums Without Default Values

最佳答案

您想使用 XMLElement Attribute而不是 XMLAttribute Attribute如果您的字段应该是 XML 中的单独元素。

例如:

<SimpleXML name="test">
<child>SomeValue</child>
</SimpleXML>

name 是一个属性,而 child 是一个元素。

关于c# - Xml 类序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com