• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5420
  • Last Modified:

"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

0
Easwaran Paramasivam
Asked:
Easwaran Paramasivam
  • 2
  • 2
2 Solutions
 
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now