Serialize protocol buffer file into xml/text format
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 syste开发者_如何学编程m.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.
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.
精彩评论