从内存流加载 Xml 问题
这是我的代码:
MemoryStream xmlStream = new MemoryStream();
XmlDocument xmlDoc = new XmlDocument();
XmlWriter xmlWriter = XmlWriter.Create(xmlStream);
//Add some elements and attributes.
xmlWriter.WriterEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
好的,现在我已经关闭了 XmlWriter,有什么方法可以再次访问 XmlStream?
如果我不关闭,那么当我想使用 xmlDoc.Load(xmlStream) 时,它会给出一个异常,提示“根元素丢失”
Here is my code:
MemoryStream xmlStream = new MemoryStream();
XmlDocument xmlDoc = new XmlDocument();
XmlWriter xmlWriter = XmlWriter.Create(xmlStream);
//Add some elements and attributes.
xmlWriter.WriterEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
Ok, now that I've closed the XmlWriter is there any way to access the XmlStream again?
If I don't close then when I want to use xmlDoc.Load(xmlStream) it gives an exception that says "Root Element is missing"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不关闭流,则可以将 Position 属性设置为 0 以返回到开头,然后创建一个 XmlReader 来读回流或使用 XmlDocument.Load 正如您尝试执行的操作。
总结一下,删除 xmlWriter.Close() 然后调用 xmlStream.Position = 0,然后调用 xmlDoc.Load(xmlStream)
If you don't close the stream you can set the Position property to 0 to go back to the start and then create an XmlReader to read the stream back or use XmlDocument.Load as you're trying to do.
To summarise, remove xmlWriter.Close() and then call xmlStream.Position = 0, then call xmlDoc.Load(xmlStream)
不是作为流 - 但您可以获取数据。
MemoryStream.ToArray
即使在关闭后也能正常工作。Not as a stream - but you can get at the data.
MemoryStream.ToArray
works even after you've closed it.不,如果您想进一步访问底层流,则不应关闭 XmlWriter,因为关闭它实际上意味着关闭底层流。您可以在使用完流后将其处置:
No, if you want to access the underlying stream further, you shouldn't close the XmlWriter since closing it actually means closing the underlying stream. You can dispose of the stream after you're done with it using:
不,您无法再访问已处置(关闭)的对象(流)。
No, you can't access disposed (closed) object (stream) anymore.