Serialize protocol buffer file into xml/text format

折月煮酒 提交于 2020-01-01 17:08:30

问题


I am using protocol buffer in .net http://code.google.com/p/protobuf-net/.

I installed the visual studio support version, which I can just write proto file in project and it generates csharp class files automatically.

A lot of times that I need to dump the files into xml(or another text format if available) file. I found that there is a method Serializer.Serialize() which takes an XmlWriter parameter. I tried to use it but it complains that the protobuf type I defined must be convertible to system.Xml.Serialization.IXmlSerializable.

In my case, what I should do in order for my type can be convertible to System.Xml.Serialization.IXmlSerializable? I don't want to change the cs file directly since it is generated on the fly when the proto file is changed.

thanks.


回答1:


Protobuf-net does not write xml; that API is intended to allow you to write protobuf data as an opaque BLOB (base-64) within an xml stream. However, protobuf-net is usually very happy to allow side-by-side use with XmlSerializer - it respects most of the same metaphors. Most likely, simply using new XmlSerializer(typeof(YourRootType)) to serialize your object will work fine. In fact, part of the internal processing for code-generation from .proto relies on this duality.

If you want explicit xml markers in your generated code (i.e. [XmlType(...)], etc), simply use the p:xml command-line option, which (if you are using the IDE tools) can also be achieved by using ;xml in the "Custom Tool Namespace" (this really isn't obvious, but it is one of the few places I found where it would accept extra data):

Basically, anything entered on the "Custom Tool Namespace" is assumed (by protobuf-net) to be a semicolon list starting with the desired namespace, followed by options for the generator; hence ;xml uses the default namespace, then adds the "xml" option, the same as doing p:xml on the command line.



来源:https://stackoverflow.com/questions/7717036/serialize-protocol-buffer-file-into-xml-text-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!