如何让 XmlSerializer 将布尔值编码为是/否? [英] How can I get XmlSerializer to encode bools as yes/no?

查看:24
本文介绍了如何让 XmlSerializer 将布尔值编码为是/否?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 xml 发送到另一个程序,该程序需要布尔标志为是"或否",而不是真"或假".

I'm sending xml to another program, which expects boolean flags as "yes" or "no", rather than "true" or "false".

我有一个类定义如下:

[XmlRoot()]
public class Foo {
    public bool Bar { get; set; }
}

当我序列化它时,我的输出如下所示:

When I serialize it, my output looks like this:

<Foo><Bar>true</Bar></Foo>

但我希望它是这样的:

<Foo><Bar>yes</Bar></Foo>

我可以在序列化时这样做吗?我宁愿不必诉诸于此:

Can I do this at the time of serialization? I would prefer not to have to resort to this:

[XmlRoot()]
public class Foo {
    [XmlIgnore()]
    public bool Bar { get; set; }

    [XmlElement("Bar")]
    public string BarXml { get { return (Bar) ? "yes" : "no"; } }
}

请注意,我还希望能够再次反序列化此数据.

Note that I also want to be able to deserialize this data back again.

推荐答案

好的,我一直在研究这个问题.这是我想出的:

Ok, I've been looking into this some more. Here's what I've come up with:

// use this instead of a bool, and it will serialize to "yes" or "no"
// minimal example, not very robust
public struct YesNo : IXmlSerializable {

    // we're just wrapping a bool
    private bool Value;

    // allow implicit casts to/from bool
    public static implicit operator bool(YesNo yn) {
        return yn.Value;
    }
    public static implicit operator YesNo(bool b) {
        return new YesNo() {Value = b};
    }

    // implement IXmlSerializable
    public XmlSchema GetSchema() { return null; }
    public void ReadXml(XmlReader reader) {
        Value = (reader.ReadElementContentAsString() == "yes");
    }
    public void WriteXml(XmlWriter writer) {
        writer.WriteString((Value) ? "yes" : "no");
    }
}

然后我将我的 Foo 类更改为:

Then I change my Foo class to this:

[XmlRoot()]
public class Foo {      
    public YesNo Bar { get; set; }
}

请注意,因为 YesNo 可以隐式转换为 bool(反之亦然),您仍然可以这样做:

Note that because YesNo is implicitly castable to bool (and vice versa), you can still do this:

Foo foo = new Foo() { Bar = true; };
if ( foo.Bar ) {
   // ... etc

换句话说,您可以将其视为布尔值.

In other words, you can treat it like a bool.

还有w00t!它序列化为:

And w00t! It serializes to this:

<Foo><Bar>yes</Bar></Foo>

它还可以正确反序列化.

It also deserializes correctly.

可能有某种方法可以让我的 XmlSerializer 自动将它遇到的任何 bool 转换为 YesNo - 但我还没有找到它.有人吗?

There is probably some way to get my XmlSerializer to automatically cast any bools it encounters to YesNos as it goes - but I haven't found it yet. Anyone?

这篇关于如何让 XmlSerializer 将布尔值编码为是/否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆