[C # | XML] XML deserialization parsing error: <XML xmlns = ''> was not expected. Add common XML to class Parsing Method

Source: Internet
Author: User

 

An error occurs when XML deserialization is used:

     public static TResult GetObjectFromXml<TResult>(string xmlString)        {            TResult result;            XmlSerializer serializer = new XmlSerializer(typeof(TResult), new XmlRootAttribute("xml"));            using (TextReader tr = new StringReader(xmlString))            {                                result = (TResult)serializer.Deserialize(tr);            }            return result;        }

To make the Results Correct, either of the two conditions must be met:
1. The class name of the tresult class is the same as that of the XML root element.
2. If the class name and root element name are inconsistent, the second parameter, new xmlrootattribute ("[root element name]"), is passed in during xmlserializer initialization to specify the root element name.
Otherwise, xmlserializer. deserialize throws the following exception:

System. invalidoperationexception: there is an error in XML document (1, 2). ---> system. invalidoperationexception: <XML xmlns = ''> was not expected.
Result stacktrace:
At Microsoft. xml. serialization. generatedassembly. xmlserializationreadertresult. read3_rootelementname ()

At system. xml. serialization. xmlserializer. deserialize (xmlreader, string encodingstyle, xmldeserializationevents events)
At system. xml. serialization. xmlserializer. deserialize (textreader)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.