XmlReader错误:根元素丢失 [英] Error with XmlReader: Root element is missing
问题描述
您好,
我正在尝试读取xml文件.我必须扫描文件两次.
第一次工作正常,但是当我尝试第二次扫描时,它抛出异常:异常:根元素丢失.类型:System.Xml.XmlException
我的代码是:
System.IO.StreamReader阅读器<-该函数接收此参数
ml er er Read ml ml ml string ml ------>正常工作,它显示xml文件
xReader.Close();
xReader = null;
xReader = XmlReader. ----->我想从头开始读一遍.因此光标必须位于第一个位置例外:根元素丢失.但是xml文件是相同的!
字符串test2 = xReader.ReadOuterXml();
您知道可能是什么问题吗?
非常感谢!
Hello,
I am trying to read an xml file. I have to scan the file two times.
The first time works fine but when I try to scan it the second time, it throws the exception: Exception: Root element is missing. Type:System.Xml.XmlException
My code is:
System.IO.StreamReader reader <- The function receives this parameter
XmlReader xReader = XmlReader.Create(reader);
while(xReader.Read())
string test = xReader.ReadOuterXml(); ------> This works fine, it shows the xml file
xReader.Close();
xReader = null;
xReader = XmlReader.Create(reader); -----> I want to read again from the beginning. So the cursor mus be located at the first position
while(xReader.Read()) --> EXCEPTION: Root element is missing. But the xml file is the same!!!
string test2 = xReader.ReadOuterXml();
Do you know what the problem could be?
Thanks a lot!
推荐答案
尊敬的约翰内斯,
创建XmlReader时不会重置基本流.第一时间一切都按预期工作,但是第二次您是从上次中断的时间(即流的末尾)开始读取的.因此,例外.
解决方案非常简单:在尝试第二次读取之前重置文件位置...
reader.BaseStream.Position = 0;
XmlReader xReader = XmlReader.Create(阅读器);
...
HTH
--mc
Hi Johannes,
the base stream is not reset when you create the XmlReader. The fist time everything works as intended, but the second time you are starting to read from the point where you left off the last time, i.e. the end of the stream. Hence the exception.
The solution is rather simple: reset the file position before you try to read for the second time...
reader.BaseStream.Position = 0;
XmlReader xReader = XmlReader.Create (reader);
...
HTH
--mc
这篇关于XmlReader错误:根元素丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!