infinity
infinity

Reputation: 1920

C# Error with XML Serialization "There is an error in XML document (2, 2)"

All, I am trying to serialize and de-serialize a class and the de-serialization is failing. There are tons of similar threads, but I am unable to resolve this. I am getting the following error "There is an error in XML document (2, 2)" Inner expection "{" was not expected."}"

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

namespace XMLSerialization
{
 [System.Xml.Serialization.XmlRootAttribute(Namespace = "",
     IsNullable = false)] 
 public class Level
 {
  private String _name;
  private String _background;

  public Level() 
  {
   _name = "LEVEL_NAME";
   _background = "LEVEL_BACKGROUND_IMAGE";
  }

  [XmlAttribute("LevelName")]
  public String LevelName
  {
   get { return _name; }
   set { _name = value; }
  }

  [XmlAttribute("Background")]
  public String Background
  {
   get { return _background; }
   set { _background = value; }
  }
 }
}

This is the code I use for de-serialization. The serialization is happening fine but the de-serialization is not going through. I think that I am doing a trivial mistake but I am unable to solve this!

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

namespace XMLSerialization
{
 class Program
 {
  static void Main(string[] args)
  {
   Level oLevel1 = new Level();

   XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
   ns.Add("", ""); 
   XmlSerializer serializer = new XmlSerializer(typeof(Level));
   TextWriter textWriter = new StreamWriter("Level1.xml");
   serializer.Serialize(textWriter, oLevel1, ns);
   textWriter.Close();

   Level oLevel2 = new Level();
   XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));
   TextReader textReader = new StreamReader("Level1.xml");
   oLevel2 = (Level)deserializer.Deserialize(textReader);
   textReader.Close();
  }
 }
}

Upvotes: 1

Views: 8225

Answers (2)

Femaref
Femaref

Reputation: 61437

You a serializing a Level and are trying to deserizalize a List<Level>.

Upvotes: 3

Lav
Lav

Reputation: 1896

I think you need to change the line

XmlSerializer deserializer = new XmlSerializer(typeof(List<Level>));

To

XmlSerializer deserializer = new XmlSerializer(typeof(Level));

Upvotes: 8

Related Questions