感觉很脏 但也许不是……使用 StringBuilder 编写 XML 可以吗?我的直觉说“虽然这感觉不对,但它的性能可能相当不错,因为它没有加载额外的库并且开销它没有执行任何额外的方法调用 XmlWriter 调用。” 总的来说,它似乎只是更少的代码。XmlWriter 有什么好处?
这是它的样子。我正在根据您来自的域构建一个 OpenSearch XML 文档。
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("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.Append("<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\">");
sb.Append(" <ShortName>Search</ShortName>");
sb.Append(" <Description>Use " + domain + " to search.</Description>");
sb.Append(" <Contact>contact@sample.com</Contact>");
sb.Append(" <Url type=\"text/html\" method=\"get\" template=\"http://" + domain + "/Search.aspx?q={searchTerms}\" />");
sb.Append(" <moz:SearchForm>http://" + domain + "/Search.aspx</moz:SearchForm>");
sb.Append(" <Image height=\"16\" width=\"16\" type=\"image/x-icon\">http://" + domain + "/favicon.ico</Image>");
sb.Append("</OpenSearchDescription>");
cachedChan = sb.ToString();
context.Cache.Insert(domain + "_opensearchdescription", cachedChan, null, DateTime.Now.AddDays(14), TimeSpan.Zero);
}
context.Response.Write(cachedChan);
}
跟进,大约 2 年后 ,我意识到我的意思是说,但完全没有说出来:使用 XML 类生成此文件的代码块与仅使用字符串相比有什么好处?有吗?这比(例如)约翰桑德的例子更糟糕吗?
我使用了吉姆舒伯特的方法,选择“我能读懂这个并且它是有道理的”而不是争夺“正确性”。我很高兴我做到了。约翰桑德的例子并没有错——但我觉得这对我想要完成的事情来说太霸道了。实用主义?也许。