How can I get XmlSerializer to encode bools as yes/no?(如何让 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 bool
s it encounters to YesNo
s as it goes - but I haven't found it yet. Anyone?
这篇关于如何让 XmlSerializer 将布尔值编码为是/否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何让 XmlSerializer 将布尔值编码为是/否?


- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01