首页 > 代码库 > [C# | XML] XML 反序列化解析错误:<xml xmlns=''> was not expected. 附通用XML到类解析方法

[C# | XML] XML 反序列化解析错误:<xml xmlns=''> was not expected. 附通用XML到类解析方法

 

使用 XML 反化时出现错误:

     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;        }

要使结果正确,必须满足两个条件中的任意一个:
1. TResult 类的类名称和 XML 根元素名一致。
2. 若类名和根元素名称不一致,在初始化
XmlSerializer 时传入第二个参数,new XmlRootAttribute("【根元素名称】"),以指定根元素名称
否则 Xmlserializer.Deserialize 抛出如下异常:

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 xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)