I’ve come across a dilemma. My C# app uses a custom file format that needs to be human-editable in a text editor, but can also be editable via the GUI in my app. This file would represent a top-level object (call it TopObject), which contains several smaller objects, which in turn contain other objects, and so forth. All of the data contained in these objects is provided in the file.
I’m stuck as how to go about the issue of loading/saving these files. C# serialization doesn’t work for me, as it breaks human-editability (binary serialization) or has “issues” with serializing collections of base classes (XML and DataContract serialization, which add text to disambiguate derived classes when serializing a base class, which makes the files more brittle to human-editing); if it weren’t for needing to have the files editable by hand, it would have been the ticket. I’ve been looking into parser generators such as GOLD and GPLEX/GPPG to parse and convert the file into the objects they represent, and it looks promising, but this only covers the one direction of loading files, not ensuring they’re saved in a correct format when writing them out.
What would be great would be a way to specify a grammar that handles both:
1) Reading a file with a specified structure and converting it into a TopObject and all its contained objects, and
2) Given a TopObject, writing its state out to a file with that same structure.
Pretty much, a single grammar that enforces import structure as well as enforces output structure.
Are there any such tools or frameworks that could help me? Is this something feasible, or am I overthinking this way too hard and there’s an easier way?
I would still use XML, but just write your own serializer. You could use the XML reader/writer classes in .Net to create a simple XML format:
I don’t know if you consider this human-readable enough, but it’s better that the stuff the .Net serializer creates. It would be easy enough to read/write recursively.
Example:
Here is a simplistic example that you can adapt. Assume I have this class:
Each
Nodehas a property, calledSomeProperty. It can also have children; moreNodesin theChildrenproperty.Here is the
mainfrom a Console application that creates some data out of this class to serialize:It calls a method called
RecursivelySerialize, which does that actual work:This method isn’t complex. To improve it, you could use Reflection to dynamically serialize any type of class. Here is the output I got (formatted nicely) when running the above code: