Best way to represent text in memory
I have 2 classes that inherit from a common base class.
Each of these specialized classes 开发者_如何学Pythonload some data from a data base, process it and then save that information in text files.
The first class represents the information as a XML document. The second class will store its information as a text file with delimiters separating fields.
What I want to do is to write a single Save method in the base class that can be used by both classes. As all classes will write to text files I was thinking in use a common representation to store their data in memory - for instance the first class will transform the XmlDocument to that common representation.
What is the best way to store this in memory, string, Stream?
Thanks
If the derived classes represent the data very differently, don't implement a common Save method for them, Those classes knows best how to Save their data. Make Save() abstract and have each of the subclass implement the saving.
There might be something in common for doing a Save() (e.g. opening the actual file, error handling). So have your base class provide a Save() method that's responsible for that which in turn calls a virtual Save(System.IO.TextWriter writer);
method that each of your subclasses implement.
Given that XML is the richer of the two formats you mention, and relatively easy to manipulate, why not have a single representation and 2 save methods?
If the input data is uniformly structured, you can likely store it cleanly in a DataSet
, and maybe load directly from your XML using DataSet.ReadXml on a TextReader
input.
If you only have one type of record to output to the delimited textfile, DataTable could be used directly - a DataSet
encapsulates multiple DataTable
s.
Another alternative might be to convert XML directly to CSV (comma = delimiter here, you could use whatever you wanted though) using XSLT as shown here by @Welbog.
精彩评论