如何在 C# 中通过 XML 序列化输出十六进制数字?
我有一些类和结构,我使用 XML 序列化来保存和调用数据,但我想要的一个功能是以十六进制表示形式输出整数。我可以在这些结构上添加任何属性来实现这一点吗?
I've got a few classes and structures that I use XML serialization to save and recall data, but a feature that I'd like to have is to output integers in hex representation. Is there any attribute that I can hang on these structure to make that happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有一点代码味道,但以下将工作:
在控制台程序中测试该类:
结果:
There's a bit of code smell, but the following will work:
Test the class in a console program:
The result:
我知道,最后一个答案是两年多前,但我一直在寻找解决方案并找到了这个帖子。但对提出的解决方案不满意,所以我尝试找到自己的解决方案:
现在您可以在序列化类中使用此类型而不是 Int32 :
结果是:
您可以调整解决方案以获得所需的确切格式并完成HInt32 结构更加“兼容 Int32”。
警告:此解决方案不能用于将属性序列化为属性。
I know, last answer was more than two years ago, but I was looking for have a solution and found this thread. But wasn't satisfied by proposed solutions so I tried to find my own solution:
Now you can use this type instead of Int32 in your serialized class :
The result is :
You can adapt the solution to get the exact format you want and complete the HInt32 struct to be more "Int32 complient".
Warning : This solution can't be use to serialize a property as an attribute.
您可以实现完全自定义的序列化,但这可能有点太多了。如何公开一个属性
MyIntegerAsHex
,它以字符串形式返回整数,格式为十六进制数:MyInteger.ToString("X");
该属性需要一个 setter ,即使它是一个计算字段,以便序列化对象中的字符串可以在反序列化时输入到新实例中。然后,您可以实现反序列化回调,或者只是将代码放入 setter 中,以便在反序列化对象时将十六进制数字解析为十进制整数:
MyInteger = int.Parse(IntegerAsHex, NumberStyles.AllowHexNumber);
因此,总而言之,您的属性将如下所示:
然后,如果您不想在 XML 文件中看到该数字作为十进制整数,只需用 [XmlIgnore] 对其进行标记即可。
You can implement fully custom serialization, but that's probably a bit much for this. How about exposing a property
MyIntegerAsHex
, that returns the integer as a string, formatted as a hexadecimal number:MyInteger.ToString("X");
The property will need a setter, even though it's a calculated field, so that the string from the serialized object can be fed into a new instance on deserialization.You can then implement a deserialization callback, or just put code in the setter, that will parse the hex number to a decimal integer when the object is deserialized:
MyInteger = int.Parse(IntegerAsHex, NumberStyles.AllowHexNumber);
So, in summary, your property would look something like this:
Then, if you didn't want to see the number as a decimal integer in the XML file, just tag it with [XmlIgnore].
我从 KeithS 和 code4life 中提出了一个稍微改进的解决方法。
这样做的好处是 xsd.exe 工具会将 type 属性设置为
xs:hexBinary
而不是xs:string
...I came up with a slightly improved variant of the workaround from KeithS and code4life.
The benefit of this is that the xsd.exe tool will set the type attribute to
xs:hexBinary
instead ofxs:string
...