XML Serialization

I came across a strange XML de-serialization error.

The data at the root level is invalid. Line 1, position 1.

Usually I will look at my xml and see where my data is incorrect. But in this case I used the Xml Serialize to create the xml that I was trying to de-serialize. Strange I thought as I’ve done this a lot in the past with no problems.

Example of a class and manager where the xml was serialized and de-serialize:

public class Animal

{

[XmlAttribute]

public string Name

{

get;

set;

}

[XmlAttribute]

public int Age

{

get;

set;

}

[XmlAttribute]

public int AgeInHumanYears

{

get;

set;

}

[XmlAttribute]

public string Type

{

get;

set;

}

}

public class AnimalManager

{

private XmlSerializer serializer = new XmlSerializer( typeof( Animal ) );

public void Save( Animal animal, string xmlFilePath )

{

// Create the File to Save the XML to

StreamWriter file = new StreamWriter( xmlFilePath );

// Save the Object to the specified stream

serializer.Serialize( file, animal );

// Close the file so that we don’t keep file locked

file.Close();

}

public Animal Load( string xmlFilePath )

{

Animal animal = null;

// Ensure that the file exists

if ( File.Exists( xmlFilePath ) )

{

// Get the File to read the data from

StreamReader file = new StreamReader( xmlFilePath );

// Deserialize the file

var obj = serializer.Deserialize( file );

// Close the file otherwise we keep a lock on the file

file.Close();

if ( animal is Animal )

animal = obj as Animal;

}

return animal;

}

}

It turns out that I was using a StringReader instead of a StreamReader to read the data back and according to this post StringReader class only encoding is encoding=”utf-16″ and the StreamWriter that I create the file with is using the utf-8 encoding. So hope this helps anyone in the future.

Johan

Advertisements

About Johan

.Net Developer
This entry was posted in XML and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s