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 bools it encounters to YesNos as it goes - but I haven't found it yet. Anyone?
这篇关于如何让 XmlSerializer 将布尔值编码为是/否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何让 XmlSerializer 将布尔值编码为是/否?
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
