views:

92

answers:

2

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?

+1  A: 

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.

Tom Cabanski
+1 XDocument/XElement are your friends. Also if using VB.NET for this is an option at all XML Literals are even easier http://blogs.msdn.com/wriju/archive/2008/02/07/vb-net-9-0-xml-literal.aspx and http://msdn.microsoft.com/en-us/library/ms364068%28vs.80%29.aspx#vb9overview_topic6
R0MANARMY
+3  A: 

I'd recommend using XMLTextWriter to build up XML documents which (quote from MSDN):

Represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.

I've used it numerous times - more performant than using XMLDocument, with the XML-safety you don't get with StringBuilder.

AdaTheDev