views:

447

answers:

4

I want to save my object to hard disk (like cache) with XmlSerializer. In this case, I don't have any problem.

However, when I want to deserialize this XML to an object, I get an error. Is there any way to deserialize XML to an unknown object or to an object that I created?

A: 

Hi,

I suppose you use Java as language.

You should consider to use SAX to parse your serialized objects. You can read the following articles to help you:

http://www.javaworld.com/jw-03-2000/jw-03-xmlsax.html

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPSAX.html

SAX makes it easy to read your XML files and to deserialize them to objects you created and you are able to manage.

Hope this helps!

reef
A: 

Another, more efficent (than either DOM or SAX) data binding approach is in this article:

vtd-xml-author
A: 

Hi, you can use SerializationHelper.DeSerializeNow as described in my post: http://borismod.blogspot.com/2008/07/nunit-serialization-test.html

internal class SerializationHelper
{
  private static readonly string DefaultFilePath = "test.dat";

  internal static void SerializeNow(object c)
  {
    SerializeNow(c, DefaultFilePath);
  }

  internal static void SerializeNow(object c, string filepath)
  {
   FileInfo f = new FileInfo(filepath);
   using (Stream s = f.Open(FileMode.Create))
   {
      BinaryFormatter b = new BinaryFormatter();
    b.Serialize(s, c);
   }
  }

  internal static object DeSerializeNow()
  {
    return DeSerializeNow(DefaultFilePath);
  }

  internal static object DeSerializeNow(string filepath)
  {
    FileInfo f = new FileInfo(filepath);
    using (Stream s = f.Open(FileMode.Open))
    {
      BinaryFormatter b = new BinaryFormatter();
      return b.Deserialize(s);
    }
  }
}
Boris Modylevsky
The question is about *XML* serialization, not binary serialization...
Thomas Levesque
Sorry, I missed the XML in the question. You can use this one:What exception are you getting?public Object DeserializeObject(String pXmlizedString) { XmlSerializer xs = new XmlSerializer(typeof(Automobile)); MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); return xs.Deserialize(memoryStream); }
Boris Modylevsky
+1  A: 

There is no way in .Net to deserialize to unknown object.

To successfully serialize/deserialize an XML object the class must have default constructor. The best way is to show us the exact error message. Can you do that?

Vasiliy Borovyak