【问题标题】:Synonymous attribute names with XmlAttribute与 XmlAttribute 同义的属性名称
【发布时间】:2017-08-29 08:38:23
【问题描述】:

我们的 XML 格式已从

<foo bar="xyz" />

<foo abc="xyz" />

。请注意属性名称从 bar 更改为 abc

XmlAttribute 是否可以同时支持两个属性名称?

我尝试用XmlAttribute 标记类成员两次,但这会导致编译时错误。

public sealed class Foo {
    [XmlAttribute("bar")] // Error: The attribute `System.Xml.Serialization.XmlAttributeAttribute' cannot be applied multiple times
    [XmlAttribute("abc")]
    public string bar;
}

知道如何在不为整个 Foo 类编写自定义反序列化的情况下处理同义词属性名称吗?

【问题讨论】:

    标签: c# xml-parsing


    【解决方案1】:

    找到了一种使用 getter 的方法,但这不是最好的解决方案:

    public sealed class Foo {
        // Both have to be public, otherwise they don't get deserialized
        [XmlAttribute("bar"), DefaultValue(null)]
        public string _bar;
        [XmlAttribute("abc"), DefaultValue(null)]
        public string _abc;
    
        public string bar {
            get {
                if (_bar != null) {
                    return _bar;
                } else {
                    return _abc;
                }
            }
        }
    }
    

    缺点是,_bar_abc 现在都是 Foo 的公共 API 的一部分。此外,我不能声明两者中的一个必须存在。

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 2018-04-06
      相关资源
      最近更新 更多