我怎样才能XmlSerializer的为en code布尔变量是/否? [英] How can I get XmlSerializer to encode bools as yes/no?
问题描述
我发送XML到另一个程序,它预计布尔标志为是或否,而不是真或假。
I'm sending xml to another program, which expects boolean flags as "yes" or "no", rather than "true" or "false".
我已经定义就像一个类:
I have a class defined like:
[XmlRoot()]
public class Foo {
public bool Bar { get; set; }
}
当我序列化,我的输出是这样的:
When I serialize it, my output looks like this:
<Foo><Bar>true</Bar></Foo>
不过,我想它是这样的:
But I would like it to be this:
<Foo><Bar>yes</Bar></Foo>
我可以做到这一点的序列化的时间呢?我想preFER不要有诉诸这样的:
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
隐式强制转换为布尔
(反之亦然),你仍然可以这样做:
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的自动施放任何布尔
的IT遇到以 YESNO
译文]它去 - 但我还没有找到它。有人吗?
There is probably some way to get my XmlSerializer to automatically cast any bool
s it encounters to YesNo
s as it goes - but I haven't found it yet. Anyone?
这篇关于我怎样才能XmlSerializer的为en code布尔变量是/否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!