是否可以将 xml 中的字符串值强制转换为 bool?

发布于 2024-08-26 05:14:27 字数 441 浏览 6 评论 0原文

假设我有这样的 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 强制“Yes”“No”为 bool 值?

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

Let's suppose I have xml like this one:

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

C# class looks like this:

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

   public string Url { get; set; }
}

Is it possible to change Active property to type bool and have XmlSerializer coerce "Yes" "No" to bool values?

Edit: Xml is received, I cannot change it. So, in fact, i'm interested in deserialization only.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

〆凄凉。 2024-09-02 05:14:27

我可能会看看第二个属性:

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

I might look at a second property:

[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();
        }
    }
}
剪不断理还乱 2024-09-02 05:14:27

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

Yes, you can implement IXmlSerializable and you will have control over how the xml is serialized and deserialized

神爱温柔 2024-09-02 05:14:27
public class Server
{
   [XmlAttribute()]
   public bool Active { get; set; }

   public string Url { get; set; }
}

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

<Server Active="false">
    <Url>http://some.url</Url>
</Server>
public class Server
{
   [XmlAttribute()]
   public bool Active { get; set; }

   public string Url { get; set; }
}

The previous class should end up in that serialized form :

<Server Active="false">
    <Url>http://some.url</Url>
</Server>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文