为什么以下反序列化没有?例外情况如下所示。请注意,我正在使用新的流序列化和反序列化来避免“流结束”错误。我也在使用新的XmlSerializer实例来避免类似的问题。
序列化工作正常。我已经回顾了许多类似命名的问题但无济于事。
例外:
System.InvalidOperationException was unhandled
Message=There is an error in XML document (0, 0).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at TestSerilalization.Program.Main(String[] args) in D:\MyDocs\Projects\dsb\Src\Apps\RecipeMgr\Other\TestSerlialization\Program.cs:line 45
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Xml.XmlException
Message=Root element is missing.
Source=System.Xml
LineNumber=0
LinePosition=0
SourceUri=""
StackTrace:
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.XmlSerializationReaderClass1.Read4_Class1()
InnerException:
代码:
static void Main(string[] args)
{
XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer( typeof( Class1 ), "http://xxx" );
Class1 c1 = new Class1();
FileStream strm = File.Create( "d:\\temp\\classes.xml" );
xmlSerializer.Serialize( strm, c1 );
strm.Close();
Class1 c2 = null;
FileStream strm2 = File.Create( "d:\\temp\\classes.xml" );
XmlSerializer xmlSerializer2 = new System.Xml.Serialization.XmlSerializer( typeof( Class1 ), "http://xxx" );
c2 = (Class1)xmlSerializer2.Deserialize( strm2 );
strm2.Close();
}
public class Class1
{
public Class1()
{
m_Class2 = new Class2();
}
public Class2 class2
{
get { return m_Class2; }
set { m_Class2 = value; }
}
private Class2 m_Class2;
}
public class Class2
{
public Class2()
{
m_Int = 999;
m_Str = "sdfsdfsdsd";
}
public int getInt
{
get { return m_Int; }
set { m_Int = value; }
}
public string getStr
{
get { return m_Str; }
set { m_Str = value; }
}
private int m_Int;
private string m_Str;
}
生成的xml:
<?xml version="1.0"?>
<Class1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://xxx">
<class2>
<getInt>999</getInt>
<getStr>sdfsdfsdsd</getStr>
</class2>
</Class1>
答案 0 :(得分:1)
File.Create
会创建一个新的空白文件
因此,您正在阅读一个空文件。
您可能想要File.Open
。