|
-
November 12th, 2009, 07:53 PM
#1
Problem serializing to Xml then deserializing
I need to serialize to Xml then at a later time deserialize to one of my classes.
Using this to serialize:
Code:
public void Serialize()
// serialize Schedule to XML file
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(MSTSSchedule));
using (StreamWriter writer = new StreamWriter("c:\\temp\\serialized.xml",true))
{
xs.Serialize(writer, this);
}
}
catch (Exception x)
{
and this to deserialize:
Code:
public MSTSSchedule DeSerialize(XmlDocument doc)
{
MSTSSchedule sch = new MSTSSchedule();
try
{
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(typeof(MSTSSchedule));
object obj = ser.Deserialize(reader);
sch = (MSTSSchedule)obj;
sch.SetResponse(ResponseCodes.RESP_ACK);
}
catch (System.Exception ex)
{
sch.SetResponse(ResponseCodes.RESP_NAK);
}
return sch;
}
and this to test it all:
Code:
try
{
schedToday.Serialize();
XmlDocument xd = new XmlDocument();
xd.LoadXml("c:\\temp\\serialized.xml");
MSTSSchedule test = schedToday.DeSerialize(xd);
}
catch (System.Exception ex)
{
I get the "[System.Xml.XmlException] = {"Data at the root level is invalid. Line 1, position 1."}" error.
Xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<MSTSSchedule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<m_Schedule>
<MSTSAppointment>
My question - shouldn't I be able to deserialize a Xml document that the .net serializer serialized??
using .Net 3.5sp1
-
November 14th, 2009, 07:54 AM
#2
Re: Problem serializing to Xml then deserializing
I have never used XmlDocument, XmlReader/Writer to serialize/deserialize classes, and I think that might be the problem ?
Here are a few functions from my Settings class I use:
Code:
private static void InternalSave(Settings settings)
{
using (FileStream fs = new FileStream(settingsFile, FileMode.Create, FileAccess.Write))
{
XmlSerializer xml = new XmlSerializer(typeof(Settings));
if (xml != null)
{
xml.Serialize(fs, settings);
}
else
{
throw new Exception("InternalSave() : Failed to create XmlSerializer");
}
}
}
private static void InternalLoad(out Settings settings)
{
settings = null;
if (File.Exists(settingsFile))
{
using (FileStream fs = new FileStream(settingsFile, FileMode.Open, FileAccess.Read))
{
XmlSerializer xml = new XmlSerializer(typeof(Settings));
if (xml != null)
{
settings = (Settings)xml.Deserialize(fs);
}
else
{
throw new Exception("InternalLoad() : Failed to create XmlSerializer");
}
}
}
if (settings == null)
settings = new Settings();
}
-
November 14th, 2009, 08:59 AM
#3
[Solved] Re: Problem serializing to Xml then deserializing
That did the trick! Thanks much!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|