views:

622

answers:

5

My application receives strings that represent objects. I have to parse the strings to get the property values for the object I'm creating. Each object will have to know the specifics about how many attributes there are, what each attribute means, etc. However, I want to avoid having each class know about how to parse the string. I'd rather pass each individual object a more fitting data structure (like a dataset or XML)...something easier to populate its properties with.

Is there anything built in to the .NET framework that is suited for this type of thing? Or should I create my own container object?

ADD:

I don't think I explained my question well enough initially. Here's an example to clarify.

Let's say my program is always passed a string of characters that represents a data table in Wiki syntax. Something like:

  {||Client:||ABC|-|Contact:||Joe Smith|-|Current revision:||1.0||}

I don't want each one of my specific wiki table objects (e.g., ClientContactTable, CustomerOrderTable, etc.) to know how to parse out | and - and }. So I'd like to write 1 chunk of code that parses the string into some "middle" tier object that I can pass to the constructor of each specific Wiki table object.

My question is: what should that middle tier object be?

+3  A: 

I suggest the BinaryFormatter.

http://www.codeguru.com/columns/dotnet/article.php/c6595

Or for direct reference:

http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx

This looks like the right thing to do. You don't really want the performance overhead of converting your strings to some XML representation and then have to deserialize it from that.
Mark Pim
+3  A: 

I might have understood your question incorrectly, but I think standard .NET serialization suits your needs:

var ms = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(ms, myObject);

// Deserialization:
var deserialized = (MyClass)formatter.Deserialize(stream);
Mehrdad Afshari
A: 

you need to parse the string data and convert it into an object or xml - i would suggest that you use string.split to create a collection (array) then use linq to create ther data structure you want and pass to an factory that returns you the right object based on param you pass to the facotry along with the data structure.

A: 

One traditional way to do it is through the System.Xml.Serialization classes. This allows you to serialize your objects to disk, and deserialize them later on. This comes with some restrictions: types should be public, have a public parameterless constructor, and have the XmlSerializer attribute on it.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;


namespace ConsoleApplication1
{
    [Serializable]
    public class Cat
    {
        DateTime _dateOfBirth;
        string _name;

        public DateTime DateOfBirth
        {
            get { return _dateOfBirth; }
            set { _dateOfBirth = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Cat() : this(DateTime.Now, "(Cat with no name)") { }

        public Cat(DateTime dateOfBirth, string name)
        {
            this.DateOfBirth = dateOfBirth;
            this.Name = name;
        }

        public override string ToString()
        {
            return string.Format("Name: {0}, DateOfBirth: {1}", Name, DateOfBirth);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Cat originalCat = new Cat(DateTime.Now, "Fluffy");
            XmlSerializer serializer = new XmlSerializer(typeof(Cat));

            MemoryStream memStream = new MemoryStream(); // can be file stream
            serializer.Serialize(memStream, originalCat);

            memStream.Position = 0; // this is just here to make this code sample work, usually you
                                    // you don't need to set your streams position manually

            Cat deserializedCat = (Cat)serializer.Deserialize(memStream);

            Console.WriteLine("originalCat.ToString(): {0}", originalCat.ToString());
            Console.WriteLine("deserializedCat.ToString(): {0}", deserializedCat.ToString());

            Console.ReadKey(true);
        }
    }
}

In general, you should be very careful with this kind of serialization. Weirdness happens when you try to serialize/deserialize objects between different versions of the same assembly.

Edit to add: The code above will serialize your object to XML. You can see the XML representation by substituting your MemoryString with a StringWriter instead (call the stringWriterInstance.ToString() method to get the XML string directly). Others have suggested using the BinaryFormatter, which does more or less the same thing, but the output is binary rather than text.

Both approaches are valid ways to serialize data, it just depends on whether you like dealing more with XML or binary data.

Juliet
A: 

If you need to store your object(s), you should use the XmlSerializer(s). This will de/serialize your objects as XML and parse them for you.

public List<_type> LoadDataFromResource<_type>(string file)
{
   List<_type> data = new List<_type>();
   FileStream str = File.OpenRead(file);
   if (str == null) return null;
   XmlSerializer sr = new XmlSerializer(data.GetType());
   if (sr == null) return null;
   data = sr.Deserialize(str) as List<_type>;
   return data;
}

public bool SaveData<_type>(string file, List<_type> data)
{
StreamWriter writer = File.CreateText(file);
if (writer == null) return false;
XmlSerializer sr = new XmlSerializer(data.GetType());
if (sr == null) return false;
sr.Serialize(writer, data);
return true;
}
Muad'Dib