title: Is using a StringBuilder for writing XML ok?
body: <p>It feels dirty. But maybe it isn't... is it ok to use a StringBuilder for writing XML? My gut instinct says "although this feels wrong, it's probably pretty darn performant because <strike>it's not loading extra libraries and overhead</strike> it's not doing whatever extra method calls XmlWriter invokes." It also seems like it's just less code in general. What's the benefit in XmlWriter?</p>
  
  <p>Here's what it looks like. I'm building an OpenSearch XML doc based on the domain you come in from.</p>
  
  <pre><code>public void ProcessRequest(HttpContext context)
  {
      context.Response.ContentType = "text/xml";
  
      string domain = WebUtils.ReturnParsedSourceUrl(null); //returns something like www.sample.com
      string cachedChan = context.Cache[domain + "_opensearchdescription"] as String;
  
      if (cachedChan == null)
      {
          StringBuilder sb = new StringBuilder();
          sb.Append("&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;");
          sb.Append("&lt;OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\"&gt;");
          sb.Append("    &lt;ShortName&gt;Search&lt;/ShortName&gt;");
          sb.Append("    &lt;Description&gt;Use " + domain + " to search.&lt;/Description&gt;");
          sb.Append("    &lt;Contact&gt;contact@sample.com&lt;/Contact&gt;");
          sb.Append("    &lt;Url type=\"text/html\" method=\"get\" template=\"http://" + domain + "/Search.aspx?q={searchTerms}\" /&gt;");
          sb.Append("    &lt;moz:SearchForm&gt;http://" + domain + "/Search.aspx&lt;/moz:SearchForm&gt;");
          sb.Append("    &lt;Image height=\"16\" width=\"16\" type=\"image/x-icon\"&gt;http://" + domain + "/favicon.ico&lt;/Image&gt;");
          sb.Append("&lt;/OpenSearchDescription&gt;");
  
          cachedChan = sb.ToString();
  
          context.Cache.Insert(domain + "_opensearchdescription", cachedChan, null, DateTime.Now.AddDays(14), TimeSpan.Zero);
      }
  
      context.Response.Write(cachedChan);
  }
  </code></pre>
  
  <p><strong>Followup, ~2 years later</strong>
  I realized that what I meant to say, and completely failed to say it is: what is the benefit of gobs of code using XML classes to generate this file, vs. just using strings? Is there one? Is this worse than (for example) John Saunder's example?</p>
  
  <p>I used Jim Schubert's method, opting for 'I can read this and it makes sense' rather than vying for 'correctness'. I'm glad I did. There's nothing wrong with John Saunder's example- but I felt that it was <em>way</em> overbearing for what I was trying to accomplish. Pragmatism? Maybe.</p>