Reputation: 6609
I am trying to create xml like this:
<CreditApplication>
<ApplicantData>
<FirstName> John </FirstName>
<LastName> Smith </LastName>
</ApplicantData>
<CoApplicantData>
<FirstName> Mary </FirstName>
<LastName> Jane </LastName>
</CoApplicantData>
</CreditApplication>
And I've defined my classes as such:
[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; }
...
}
And further down in the CreditApplication class I have references to enumerations that are defined elsewhere in my program that also need to be made serilizable.
When I actually run the program and try to serlizize the class with:
XmlSerializer applicantXMLSerializer = new XmlSerializer(typeof(CreditApplication));
StringWriter applicantStringWriter = new StringWriter();
XmlWriter applicantXmlWriter = XmlWriter.Create(applicantStringWriter);
applicantXMLSerializer.Serialize(applicantXmlWriter, application);
var applicantXML = applicantStringWriter.ToString();
But I get the error: There was an error reflecting type 'Models.Credit.CreditApplication'
Does anyone have any idea what I'm doing wrong?
EDIT:
I've updated the above code to reflect the changes suggested. There are other issues that have presented themselves though.
I have an enum defined as such:
[DataContract]
public enum Relationship
{
Spouse = 4,
ResidesWith = 1,
Parent = 2,
Other = 3,
PersonalGuarantor = 5,
CoApplicant = 6
}
As seen above, zero is not a defined option. Because of this, there is no default value. I have designed the program around the idea that a relationship that is not set defaults to zero. That way I can easily see if a value has been set. If I have zero defined and then have it initialize to "No Relationship" or something like that, then there is no way to tell if the user set the value to "No Relationship", or if they simply did not choose an option.
Moved:
XML Serialization of Enums Without Default Values
Upvotes: 2
Views: 487
Reputation: 8047
You want to use the XMLElement Attribute instead of the XMLAttribute Attribute if your fields are supposed to be separate elements in the XML.
For example:
<SimpleXML name="test">
<child>SomeValue</child>
</SimpleXML>
name
is an attribute, whereas child
is an element.
Upvotes: 2