从内存流加载 Xml 问题

发布于 2024-12-05 08:00:48 字数 403 浏览 0 评论 0原文

这是我的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

哥,最终变帅啦 2024-12-12 08:00:48

如果您不关闭流,则可以将 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)

蒲公英的约定 2024-12-12 08:00:48

不是作为流 - 但您可以获取数据。

MemoryStream.ToArray 即使在关闭后也能正常工作。

Not as a stream - but you can get at the data.

MemoryStream.ToArray works even after you've closed it.

夏末 2024-12-12 08:00:48

不,如果您想进一步访问底层流,则不应关闭 XmlWriter,因为关闭它实际上意味着关闭底层流。您可以在使用完流后将其处置:

xmlStream.Dispose();

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:

xmlStream.Dispose();
后eg是否自 2024-12-12 08:00:48

不,您无法再访问已处置(关闭)的对象(流)。

No, you can't access disposed (closed) object (stream) anymore.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文