与 XmlDocument 或相关创建 XML 文档相比,使用 StringBuilder 有何优点?
这可能有点代码味道,但我看到它是一些生产代码,即使用 StringBuilder 而不是 XmlDocument 创建 XML 文档时。在某些情况下,这些是一次写入操作(例如创建文档并将其保存到磁盘),而其他操作则将构建的字符串传递到 XmlDocument 以执行 XslTransform 到返回给客户端的文档。
如此明显的问题:以这种方式做事是否有优点,是否应该根据具体情况进行,或者这是错误的做事方式吗?
This might be a bit of a code smell, but I have seen it is some production code, namely the use of StringBuilder as opposed to XmlDocument when creating XML documents. In some cases these are write once operations (e.g. create the document and save it to disk) where as others are passing the built string to an XmlDocument to preform an XslTransform to a document that is returned to the client.
So obvious question: is there merit to doing things this way, is it something that should be done on a case-by-case basis, or is this the wrong way of doing things?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用 XMLTextWriter 构建 XML 文档其中(引自 MSDN):
我已经使用过它很多次 - 比使用 XMLDocument 性能更高,并且具有 StringBuilder 所没有的 XML 安全性。
I'd recommend using XMLTextWriter to build up XML documents which (quote from MSDN):
I've used it numerous times - more performant than using XMLDocument, with the XML-safety you don't get with StringBuilder.
使用 XmlDocument 创建 XML 很麻烦,因此大多数人都懒得使用它。 StringBuilder 是轻量级的,但不了解 XML,因此根本不验证结构。使用 LINQ to XML,您可以两全其美。它允许您轻松地编写有效的 XML,而无需太多愚蠢的开销。如果您不熟悉 Linq 的使用,请查看这篇文章到 XML 来编写 XML。
XmlDocument is a pain to use for creating XML so most folks do not bother to use it. StringBuilder is light weight but does not know XML so doesn't validate structure at all. You can get the best of both worlds with LINQ to XML. It allows you to author valid XML easily without much goofy overhead. Check out this article if you are not familiar with the use of Linq to XML to author XML.