XML Deserialization Newbie Question

B

Bill Henning

Hi there.... I'm trying to figure out how to do simple XML serialization
however whenever I try to deserialize from XML, I get a System Error
("System.Xml.XmlException: The root element is missing.").

Could someone try running this sample code to tell me what I'm doing wrong?
I'm just serializing an int and trying to call CanDeserialize on it and
that's where the exception occurs. Thanks so much in advance!


// ----------------------------------------------------
string xml;
int c = 100;
{
System.Xml.Serialization.XmlSerializer serializer = new
System.Xml.Serialization.XmlSerializer(c.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream,
null);
serializer.Serialize(writer, c);
stream.Position = 0;
xml = new System.IO.StreamReader(stream).ReadToEnd();
stream.Close();
}
Console.WriteLine(xml);
{
System.Xml.Serialization.XmlSerializer serializer = new
System.Xml.Serialization.XmlSerializer(c.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream,
null);
writer.WriteRaw(xml);
stream.Position = 0;
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream);
Console.WriteLine(serializer.CanDeserialize(reader));
}
return;
// ----------------------------------------------------
 
J

Jared Parsons [MSFT]

Try adding a call to writer.Flush() just before you reset the stream
position to 0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top