Reputation: 11165
I have the following xml and I want to deserialize it blindly to this class:
public class FieldTranslations
{
public FieldTranslation FirstName { get; set; }
public FieldTranslation LastName { get; set; }
public FieldTranslation Email { get; set; }
public FieldTranslation PhoneNumber { get; set; }
public FieldTranslation Country { get; set; }
}
public class FieldTranslation
{
public string Title { get; set; }
public string Helper { get; set; }
public string ErrorMessage { get; set; }
}
XML:
<FieldsTranslations>
<FirstName>
<Title>First Name</Title>
<Helper>please insert your first name</Helper>
<ErrorMessage>First name is suppose to be more that 2 characters</ErrorMessage>
</FirstName>
<LastName>
<Title>Last Name</Title>
<Helper>please insert your last name</Helper>
<ErrorMessage>Last name is suppose to be more that 2 characters</ErrorMessage>
</LastName>
<Email>
<Title>Email</Title>
<Helper>please insert your email address (ex:[email protected])</Helper>
<ErrorMessage>email address is incorrect. the format should be: ex: [email protected]</ErrorMessage>
</Email>
<PhoneNumber>
<Title>Phone Number</Title>
<Helper>Please insert your phone number ex:(972) 14262315</Helper>
<ErrorMessage>Phone number is incorrect see example: (972) 14262315 </ErrorMessage>
</PhoneNumber>
<Country>
<Title>Country</Title>
<Helper>Please choose your country of residence</Helper>
<ErrorMessage>Country must be chosen</ErrorMessage>
</Country>
</FieldsTranslations>
When I say blindly it means that each time Im adding a member to FieldTranslations
, if there is name match, it will be deserialized without explicitly doing anything.
Upvotes: 1
Views: 78
Reputation: 1062965
var serializer = new XmlSerializer(typeof(FieldTranslations));
var obj = (FieldTranslations)serializer.Deserialize(source);
with one tweak to the classes (where the class name and root element name are not an exact match):
[XmlRoot("FieldsTranslations")]
public class FieldTranslations
{
// ... your code as before
}
Upvotes: 3