3

假设我有这样的 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,我无法更改它。所以,事实上,我只对反序列化感兴趣。

4

3 回答 3

3

我可能会看第二个属性:

[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();
        }
    }
}
于 2010-03-24T13:19:52.803 回答
2

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

于 2010-03-24T13:14:29.560 回答
0
public class Server
{
   [XmlAttribute()]
   public bool Active { get; set; }

   public string Url { get; set; }
}

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

<Server Active="false">
    <Url>http://some.url</Url>
</Server>
于 2010-03-24T13:17:11.990 回答