c# - Xml 类序列化错误

标签 c# xml xml-serialization

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

相关文章:

c# - Xamarin Forms WebView 缓存 : GoBack() doesn't call Navigating event

c# - 统一: No parameterless constructor defined for this object.

c# - 通过 WebApi 调用从页面下载 excel 文件

c# - WCF 中 IsWrapped 属性的用途是什么

c# - 如何使用 XML 序列化没有无参数构造函数的密封类?

c# - 如何使用 excellibrary.dll 设置 excel 单元格的字体大小

python - 属性错误 : module 'copy' has no attribute 'deepcopy'

xml - java 的 node.getTagName 的 scala 函数

c# - XML 文档 (30, 14) FormatException : Input string was not in a correct format. 中存在错误?

java - jaxb设置字符串类型