XML反序列化类的成员列表

时间:2013-11-10 21:59:42

标签: c# xml serialization

我有以下xml,我想盲目地将它反序列化到这个类:

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:jerry.seinfeld@domain.com)</Helper>
        <ErrorMessage>email address is incorrect. the format should be: ex: jerry.seinfeld@domain.com</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>

当我盲目地说这意味着每次我向FieldTranslations添加一个成员时,如果有名称匹配,它将被反序列化而不明确地做任何事情。

1 个答案:

答案 0 :(得分:3)

var serializer = new XmlSerializer(typeof(FieldTranslations));
var obj = (FieldTranslations)serializer.Deserialize(source);

对类进行一次调整(类名和根元素名称不完全匹配):

[XmlRoot("FieldsTranslations")]
public class FieldTranslations
{
    // ... your code as before
}