2015-10-15 88 views
2

我想反序列化XML到對象,但不斷得到以下異常,我使用InvalidOperationException異常對反序列化

` 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我使用看起來正確的,但不知道爲什麼錯誤是

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 

代碼未來

以下是XML的示例部分

<?xml version="1.0" encoding="utf-8"?> 
<ObjectSchema> 
    <Controllers> 



    </Controllers> 
</ObjectSchema> 

任何幫助,將不勝感激

感謝

+0

有關此例外情況的任何有用的信息,將不勝感激 – Amit

+0

例外說''根元素丟失'...你的Xml無效。你如何序列化你的對象到Xml?你有沒有失敗的XML的樣本? – pinkfloydx33

+0

在問題中添加了XML – Amol

回答

0

沒有什麼錯的代碼和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); 
     } 

}