繁体   English   中英

如何反序列化XML代码段以配置已经存在的对象?

[英]How can I deserialize an XML snippet to configure an already existing object?

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

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>

简单的方法

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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM