【问题标题】:Is it possible to coerce string values in xml to bool?是否可以将 xml 中的字符串值强制为 bool?
【发布时间】:2010-03-24 13:07:42
【问题描述】:

假设我有这样的xml:

<Server Active="No">
    <Url>http://some.url</Url>
</Server>

C# 类如下所示:

public class Server
{
   [XmlAttribute()]
   public string Active { get; set; }

   public string Url { get; set; }
}

是否可以将 Active 属性更改为类型 bool 并让 XmlSerializer 强制“是”“否”为布尔值?

编辑:Xml 已收到,我无法更改。所以,事实上,我只对反序列化感兴趣。

【问题讨论】:

    标签: c# xml-serialization coercion


    【解决方案1】:

    我可能会看第二个属性:

    [XmlIgnore]
    public bool Active { get; set; }
    
    [XmlAttribute("Active"), Browsable(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public string ActiveString {
        get { return Active ? "Yes" : "No"; }
        set {
            switch(value) {
                case "Yes": Active = true; break;
                case "No": Active = false; break;
                default: throw new ArgumentOutOfRangeException();
            }
        }
    }
    

    【讨论】:

    • 这是一种非常巧妙的方法。我唯一的抱怨是 ActiveString 将在同一项目的 IntelliSense 中可见。
    • @Kugel - 在 same 项目中,是的。不过,[EditorBrowsable(...)] 至少会尝试处理 other 项目。
    【解决方案2】:

    是的,您可以实现IXmlSerializable,并且您将控制 xml 的序列化和反序列化方式

    【讨论】:

    • 但是,在一般情况下(如果我们假设有嵌套对象等),这是一个非常可怕的接口,必须实现。
    【解决方案3】:
    public class Server
    {
       [XmlAttribute()]
       public bool Active { get; set; }
    
       public string Url { get; set; }
    }
    

    上一个类应该以该序列化形式结束:

    <Server Active="false">
        <Url>http://some.url</Url>
    </Server>
    

    【讨论】:

    • ...这与 OP 的要求不符(他无法更改 xml)?
    猜你喜欢
    • 2022-12-20
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2021-04-20
    • 2021-04-15
    相关资源
    最近更新 更多