我想将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>
任何帮助将不胜感激
由于
答案 0 :(得分:0)
代码和XML没有任何问题。这是因为StreamReader
。流是只有前向模式的读者一旦达到EOF,当尝试从状态EOF 读取相同的流时,XMLSerializer会抛出错误,即在文件末尾找到光标并且没有根标签
而不是使用允许多个读数的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);
}
}