Friday, July 08, 2011

Error Deserializing XML: There is an error in XML document (2, 2)

While working with some XML documents, I ran into this cryptic error: “There is an error in XML document (2, 2).” The problem turned out to be a surprising case sensitivity in the C# code. When I was trying to deserialize from XML to an object, the XML elements didn’t match the case of the class properties.

Here is my original XML file:

<?xml version="1.0" encoding="utf-8" ?>

Test class:

public class Test
  public string Name { get; set; }

And the code that I was using to deserialize the XML into the Test class object.

string xmlFile = String.Concat(HttpContext.Current.Request.PhysicalApplicationPath, "test.xml"); System.IO.StreamReader reader = System.IO.File.OpenText(xmlFile);
XmlSerializer xs = new XmlSerializer(typeof(ReportTemplate));
Test testData = (ReportTemplate)xs.Deserialize(reader);

The solution was quite simple. The case of the XML tags did not match the case of the class properties. By changing them to match, I resolved the error. Here is the working XML:

<?xml version="1.0" encoding="utf-8" ?>

BTW – If the root element case matches, but one of the sub-elements does not, you will see the beloved error “Object reference not set to an instance of an object.


Unknown said...

What a helpful, detailed post! THANK YOU!!

Unknown said...

Very helpful