使用 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)
[C# | XML] XML 反序列化解析错误:<xml xmlns=''> was not expected. 附通用XML到类解析方法
时间: 2024-10-20 04:24:33