编写 XML 最快的方法是什么
我需要经常创建 XML 文件,我选择 XmlWrite 来完成这项工作,我发现它花了很多时间在 WriteAttributeString 之类的事情上(在某些情况下我需要编写大量属性),我的问题是有没有更好的方法来创建 xml 文件?提前致谢。
I need create XML files frequently and I choose XmlWrite to do the job, I found it spent much time on things like WriteAttributeString ( I need write lots of attributes in some cases), my question is are there some better way to create xml files? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
据我所知,最快的方法是将文档结构编写为纯字符串并将其解析为 XDocument 对象:
现在您将拥有一个结构化且可供使用的 XDocument 对象,您可以在其中填充数据。此外,您甚至可以将完全结构化和填充的 XML 解析为字符串并从那里开始。此外,您始终可以使用结构化 XElement,如下所示:
这将生成:
Fastest way that I know is two write the document structure as a plain string and parse it into an XDocument object:
Now you will have a structured and ready to use XDocument object where you can populate with your data. Also, you can even parse a fully structured and populated XML as string and start from there. Also you can always use structured XElements like this:
Which will generate:
XmlSerializer
您只需定义类的层次结构你想要序列化,仅此而已。此外,您可以通过应用于属性的一些属性来控制架构。
XmlSerializer
You only have to define hierarchy of classes you want to serialize, that is all. Additionally you can control the schema through some attributes applied to your properties.
通过例如 FileStream(通过手动创建的代码)将其直接写入文件。这可以变得非常快,但也很难维护。与往常一样,优化带有奖品标签。
另外,不要忘记“过早的优化是万恶之源”。
Write it directly to a file via for example a
FileStream
(through manually created code). This can be made very fast, but also pretty hard to maintain. As always, optimizations comes with a prize tag.Also, do not forget that "premature optimization is the root of all evil".
使用匿名类型并序列化为 XML 是一种有趣的方法,正如 此处提到的
Using anonymous types and serializing to XML is an interesting approach as mentioned here
多少时间...是10毫秒、10秒还是10分钟...以及编写Xml的整个过程有多少时间?
并不是说你不应该优化,但在我看来,这取决于你想花多少时间来优化流程的这一点。最后,你想走得越快,在这种情况下维护起来就越复杂(个人观点)。
How much is much time...is it 10 ms, 10 sec or 10 min...and how much of the whole process that writes an Xml is it?
Not saying that you shouldn't optimize but imo it's a matter of how much time do you want to spend optimizing that slight bit of a process. In the end the faster you wanna go, the more complex it will be to maintain in this case (personal opinion).
我个人喜欢使用
XmlDocument
类型。编写节点时仍然有点繁重,但属性是单行的,而且总而言之比使用 Xmlwrite 更简单。I personally like to use
XmlDocument
type. It's still a bit heavy when writing nodes but attributes are one-liner, and all in all way simpler that using Xmlwrite.