在具有 XmlTypeAttribute 的生成类上实现 IXmlSerializable
基本上,最初的问题是我需要将布尔值序列化为 0 或 1。我找到的解决方案是实现 IXmlSerialized,我就是这样做的。不幸的是,我尝试序列化的类是根据架构生成的代码,并且上面有一个 XmlTypeAttribute。当我尝试使用以通常方式创建的 XmlSerializer(new XmlSerializer(type)
)来(反)序列化对象时,它会抛出此异常:
System.InvalidOperationException:只能指定 XmlRoot 属性对于类型______,请使用XmlSchemaProviderAttribute 来指定架构类型。
立即想到两个选项:
1) 删除生成的代码中的属性。 每次重新生成代码时都必须进行此更改。
2) 创建序列化程序时使用 XmlAttributeOverrides 对象来删除属性。这需要代码库的其余部分“知道”它需要覆盖该属性。此外,抛出的异常完全没有提供任何关于需要做什么来修复它的线索。
这两个选项都有点臭。还有第三种选择吗?
Basically, the initial problem is I need to make a boolean value serialize as 0 or 1. The solution I found was to implement IXmlSerializable, which I did. Unfortunately the class I'm trying to serialize is generated code off a schema and has an XmlTypeAttribute on it. When I try to (de)serialize the object with the XmlSerializer created in the usual manner ( new XmlSerializer(type)
) it throws this exception:
System.InvalidOperationException: Only XmlRoot attribute may be specified for the type ______ Please use XmlSchemaProviderAttribute to specify schema type.
Two options come to mind immediatly:
1) remove the attribute in the generated code.
This change would have to be made every time the code was re-generated.
2) Use an XmlAttributeOverrides object when creating the serializer to remove the attribute. This would require the rest of the code base to "know" that it needs to override that attribute. Also, the exception thrown gives absolutly no clue as to what needs to be done to fix it.
Both options kinda stink. Is there a third option?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我有同样的问题,对于我删除 IXMLSerialized 作品,我不使用它,并且您是否尝试使用属性中的某些逻辑来隐藏 true 或 false ?像这样:
当然,您应该增强属性并进行更多检查,但这就是想法。
I have the same problem, for me removing the IXMLSerializable works, I don't use it, and have you tried to hide the true or false with a some logic in the properties? Like this:
Of course you should enhance the properties and do more checking, but that's the idea.