使用 .NET XmlTextWriter 检查输出大小
我需要生成一个 XML 文件,并且需要将尽可能多的数据放入其中,但文件大小有限制。所以我需要继续插入数据,直到不再有任何内容为止。如何计算 XML 文件的大小而不将其重复写入文件?
I need to generate an XML file and i need to stick as much data into it as possible BUT there is a filesize limit. So i need to keep inserting data until something says no more. How do i figure out the XML file size without repeatably writing it to file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我同意约翰·桑德斯的观点。下面的一些代码基本上可以完成他所说的操作,但作为 XmlSerializer(除了 FileStream)并使用 MemoryStream 作为中间存储。不过,延长流量可能更有效。
要使用它,您可以使用最大文件长度对其进行初始化,然后使用基本文件路径和对象进行序列化。
这个特定的示例将生成一个 xml 文件,分为
I agree with John Saunders. Here's some code that will basically do what he's talking about but as an XmlSerializer except as a FileStream and uses a MemoryStream as intermediate storage. It may be more effective to extend stream though.
To use it, you'd initialize it with the max file length and then serialize using the base file path and then the object.
This particular example will generate an xml file partitioned into
一般来说,即使关闭所有打开的标记,也不能在任意位置破坏 XML 文档。
但是,如果您需要将 XML 文档拆分为多个文件,每个文件不超过一定的大小,那么您应该创建您自己的
Stream
类的子类型。这个“PartitionedFileStream
”类可以写入特定文件,直至达到大小限制,然后创建一个新文件,并写入该文件,直至达到大小限制,等等。这将为您留下多个文件连接起来构成一个有效的 XML 文档。
一般情况下,结束标签不起作用。考虑一种 XML 格式,该格式必须包含一个元素 A,后跟一个元素 B。如果在写入元素 A 后关闭标签,则您没有有效的文档 - 您需要写入元素 B。
但是,在以下特定情况下一个简单的站点地图文件,可能只需关闭标签即可。
In general, you cannot break XML documents at arbitrary locations, even if you close all open tags.
However, if what you need is to split an XML document over multiple files, each of no more than a certain size, then you should create your own subtype of the
Stream
class. This "PartitionedFileStream
" class could write to a particular file, up to the size limit, then create a new file, and write to that file, up to the size limit, etc.This would leave you with multiple files which, when concatenated, make up a valid XML document.
In the general case, closing tags will not work. Consider an XML format that must contain one element A followed by one element B. If you closed the tags after writing element A, then you do not have a valid document - you need to have written element B.
However, in the specific case of a simple site map file, it may be possible to just close the tags.
您可以向
XmlTextWriter
询问它的BaseStream
,并检查它的Position
。正如其他人所指出的,您可能需要保留一些空间才能正确关闭 Xml。
You can ask the
XmlTextWriter
for it'sBaseStream
, and check it'sPosition
.As the other's pointed out, you may need to reserve some headroom to properly close the Xml.