c# - 反序列化具有唯一属性的重复 XML 元素

标签 c# xml xml-serialization xmlserializer

我有以下 XML 结构:

<Response>
  <Value Name="ID">1</Value>
  <Value Name="User">JSmith</Value>
  <Value Name="Description">Testing 123</Value>
</Response>

如何反序列化它,以便值名称是类的属性,文本值是属性的值?

请注意,值名称永远不会更改,因此 Name="ID" 将始终存在。

到目前为止,这是我的类(class):

[Serializable]
[XmlRoot("Response")]
public class ReportingResponse
{
    // [What goes here?]
    public string ID { get; set; }

    // [...]
    public string User { get; set; }

    // [...]
    public string Description { get; set; }
}

最佳答案

XML 被构造为名称/值对的集合,而不是具有预定义属性的类,因此反序列化它会更容易、更自然。

如果您决定反序列化为一个类,假设您正在使用 XmlSerializer ,您可以为此目的引入名称/值对的代理数组,如下所示:

public class NameValuePair
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlText]
    public string Value { get; set; }

    public override string ToString()
    {
        return string.Format("Name={0}, Value=\"{1}\"", Name, Value);
    }
}

[Serializable]
[XmlRoot("Response")]
public class ReportingResponse
{
    [XmlElement(ElementName="Value")]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public NameValuePair[] XmlNameValuePairs
    {
        get
        {
            return NameValuePairExtensions.GetNamedValues(this).ToArray();
        }
        set
        {
            NameValuePairExtensions.SetNamedValues(this, value);
        }
    }

    [XmlIgnore]
    public string ID { get; set; }

    [XmlIgnore]
    public string User { get; set; }

    [XmlIgnore]
    public string Description { get; set; }
}

然后进行一些反射来自动加载数组:

public static class NameValuePairExtensions
{
    public static List<NameValuePair> GetNamedValues<T>(T obj)
    {
        if (obj == null)
            throw new ArgumentNullException();
        var type = obj.GetType();
        var properties = type.GetProperties();
        List<NameValuePair> list = new List<NameValuePair>();
        foreach (var prop in properties)
        {
            if (prop.PropertyType == typeof(string))
            {
                var getter = prop.GetGetMethod();
                var setter = prop.GetSetMethod();

                if (getter != null && setter != null) // Confirm this property has public getters & setters.
                {
                    list.Add(new NameValuePair() { Name = prop.Name, Value = (string)getter.Invoke(obj, null) });
                }
            }
        }
        return list;
    }

    public static void SetNamedValues<T>(T obj, IEnumerable<NameValuePair> values)
    {
        if (obj == null || values == null)
            throw new ArgumentNullException();
        var type = obj.GetType();
        foreach (var value in values)
        {
            var prop = type.GetProperty(value.Name);
            if (prop == null)
            {
                Debug.WriteLine(string.Format("No public property found for {0}", value));
                continue;
            }
            try
            {
                prop.SetValue(obj, value.Value, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception setting " + value.ToString() + " : \n" + ex.ToString());
            }
        }
    }
}

这将使用所有字符串值属性名称和值填充数组。您可能需要更智能的东西,在这种情况下,手动填充数组,使用自定义属性来标记属性以指示要导出的属性,或者其他可能更合适的方法。

关于c# - 反序列化具有唯一属性的重复 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26960542/

相关文章:

java - xstream 属性相互依赖性

c# - 序列化在运行时创建的类

c# - Unity销毁实例化克隆停止实例化

c# - Azure Blob 和表存储以更简单的方式重写代码

c# - 如何使用带有 ssl 的证书通过 https ://连接到 web 服务

java - Spring MVC : Login and logout functions?

visual-studio-2005 - 为什么 Visual Studio 2005 不会生成 Xml 序列化程序集?

c# - 应用程序锁定文件

python - View 找不到字段

xml - XSLT 转换 - 动态元素名称