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)