"There is an error in XML document (0, 0)." Root element is missing

I get exception "There is an error in XML document (0, 0)." Root element is missing while deserializing an xml string. I give the code below.

What could be reason for the exception and how to resolve it? Please do assist.


 
  public static object FromXml(string xmlString, Type type)
        {
            object objectToReturn = null;
            var serializer = new XmlSerializer(type);
            using (var stream = new StringReader(xmlString))
            {
                try
                {
                    objectToReturn = serializer.Deserialize(stream);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("Failed to " + "create object from xml string", ex);
                }
            }

            return objectToReturn;
        }

Open in new window



The xml file looks like below:

<?xml version="1.0"?><SettlementInfo><Id>10000019</Id><Name>Easwar</Name>.....</SettlementInfo>

Open in new window

LVL 16
Easwaran ParamasivamAsked:
Who is Participating?
 
Meir RivkinFull stack Software EngineerCommented:
what is the type passed to the function?
try this generix xml deserializer instead:
 public static T DeserializeFromXml<T>(string xml)
        {
            T result;

            var ser = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }

Open in new window

0
 
käµfm³d 👽Commented:
Are you certain that is the XML being passed to the serializer? Have you tried stepping through that bit of code and inspecting your xmlString variable to see that is correct?
0
 
Easwaran ParamasivamAuthor Commented:
In the XML file I've replaced SettlementInfo with VIPSettlementInfo and it works fine.
0
 
Easwaran ParamasivamAuthor Commented:
Your information is useful.
0
 
käµfm³d 👽Commented:
It would tickle me to no end to know how making the method generic solved the issue, especially considering that the algorithm is exactly the same.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.