反序列化的InvalidoperationException

本文关键字:InvalidoperationException 反序列化 | 更新日期: 2023-09-27 18:17:54

我想将XML反序列化为对象,但不断得到以下异常

System.InvalidOperationException: There is an error in XML document (0, 0).     ---> System.Xml.XmlException: Root element is missing.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.MoveToContent()
at   Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderBAObjectSchema.Read18_BAObjectSchema()
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   at Siemens.BASys.BAObjectCreator.SchemaHandler.Deserialize[T](String path, Boolean throwException) in ....'SchemaHandler.cs:line 34

代码我正在使用

` public static T Deserialize<T>(string path, bool throwException)
    {
        T root = default(T);
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (TextReader reader = new StreamReader(fs))
                {
                    //XmlSerializer serializer = new XmlSerializer(typeof(T));
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    root = (T)serializer.Deserialize(reader);
                }
            }
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.ToString());
        }
        return root;
    }`

我使用的XML看起来是正确的,但不确定为什么会出现错误

下面是XML

的示例部分
<?xml version="1.0" encoding="utf-8"?>
<ObjectSchema>
  <Controllers>

  </Controllers>
</ObjectSchema>

如有任何帮助,不胜感激

谢谢

反序列化的InvalidoperationException

代码和XML没有任何问题。这是因为StreamReader。一旦流达到EOF, XMLSerializer就会在试图从状态为EOF 的相同流中读取时抛出错误。在文件末尾找到游标,并且没有根标记。

而不是使用TextReader用户XMLTextReader允许多次读取。

using (FileStream fs = new FileStream(path, FileMode.Open))
 {
    using (XmlReader reader = new XmlTextReader(fs))
      {
         XmlSerializer serializer = new XmlSerializer(typeof(T));
         root = (T)serializer.Deserialize(reader);
      }
 }
相关文章:
  • 没有找到相关文章