如何反序列化XML片段以配置现有对象?

时间:2011-03-22 21:11:53

标签: c# .net xml-serialization

这是我的场景,我有以下类,我想让构造函数反序列化该类的一些元素。我真的不想在这里使用工厂方法。

public abstract class AccessLevelAgentBase : IAccessLevelAgent
{
    public List<AccessLevel> AccessLevels { get; set; }

    [XmlElement]
    public string PasswordPrompt { get; set; }

    [XmlElement]
    public string GetAccessLevelKeystroke { get; set; }

    [XmlElement]
    public int Doohicky { get; set;}

    public AccessLevelAgentBase(XElement agentElement)
    {
        // Some Mojo Here to take agentElement and serialize
        // from the XML below to set the values of PasswordPrompt,
        // GetAccessLevelKeystroke, and Doohicky.
    }
}

XML:

<AccessLevelAgent>
    <PasswordPrompt> Password ?: </PasswordPrompt>
    <PromptCommand>Ctrl+X</PromptCommand>
    <Doohicky>50</Doohicky>
</AccessLevelAgent>

1 个答案:

答案 0 :(得分:3)

简单的方法......

public AccessLevelAgentBase(XElement agentElement)     
{
    this.AccessLevels  = (string)agentElement.Element("AccessLevels");
    this.GetAccessLevelKeystroke = (string)agentElement.Element("GetAccessLevelKeystroke");
    this.Doohicky = (int)agentElement.Element("Doohicky");
} 

......不那么简单......

public AccessLevelAgentBase(XElement agentElement)
{
    var type = this.GetType();
    var props = from prop in type.GetProperties()
                let attrib = prop.GetCustomAttributes(typeof(XmlElementAttribute), true)
                                    .OfType<XmlElementAttribute>()
                                    .FirstOrDefault()
                where attrib != null
                let elementName = string.IsNullOrWhiteSpace(attrib.ElementName) 
                                            ? prop.Name 
                                            : attrib.ElementName
                let value = agentElement.Element(elementName)
                where value != null
                select new
                {
                    Property = prop,
                    Element = value,
                };

    foreach (var item in props)
    {
        var propType = item.Property.PropertyType;
        if (propType == typeof(string))
            item.Property.SetValue(this, (string)item.Element, null);
        else if (propType == typeof(int))
            item.Property.SetValue(this, (int)item.Element, null);
        else 
            throw new NotSupportedException();
    }
}