Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4996
  • 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

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

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