使用StringBuilder编写XML好吗?

Jac*_*son 11 c# xml asp.net stringbuilder

感觉很脏.但也许它不是......使用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);
}
Run Code Online (Sandbox Code Playgroud)

跟进,大约2年后, 我意识到我的意思,并完全没有说出来:使用XML类生成这个文件的代码的优势是什么,而不仅仅是使用字符串?有吗?这比(例如)John Saunder的例子更糟吗?

我使用了Jim Schubert的方法,选择了"我能读懂它并且它有意义",而不是争取'正确性'.我很高兴我做到了.这没有什么错与约翰·Saunder的示例-但我觉得这是这样为我试图完成霸道.实用主义?也许.

Joh*_*ers 15

那是非常错的.使用其中一个了解XML的.NET API来编写XML.

使用a System.Xml.XmlWriter不会通过加载"任何额外的库"导致任何性能问题.


使用XML API的原因是他们理解XML的规则.例如,他们将知道需要在元素内引用的字符集,以及需要在属性中引用的不同集合.

在您的情况下,这可能不是问题:也许您确定domain不会有任何需要引用的字符.在任何更广泛的情况下,最好让XML API执行XML - 他们知道如何操作 - 因此您不必自己完成.


以下是使用LINQ to XML生成有效XML的简单示例:

public static string MakeXml()
{
    XNamespace xmlns = "http://a9.com/-/spec/opensearch/1.1/";
    XNamespace moz = "http://www.mozilla.org/2006/browser/search/";
    string domain = "http://localhost";
    string searchTerms = "abc";
    var doc = new XDocument(
        new XDeclaration("1.0", "UTF-8", "yes"),
        new XElement(
            xmlns + "OpenSearchDescription",
            new XElement(xmlns + "ShortName", "Search"),
            new XElement(
                xmlns + "Description",
                String.Format("Use {0} to search.", domain)),
            new XElement(xmlns + "Contact", "contact@sample.com"),
            new XElement(
                xmlns + "Url",
                new XAttribute("type", "text/html"),
                new XAttribute("method", "get"),
                new XAttribute(
                    "template",
                    String.Format(
                        "http://{0}/Search.aspx?q={1}",
                        domain,
                        searchTerms))),
            new XElement(
                moz + "SearchForm",
                String.Format("http://{0}/Search.aspx", domain)),
            new XElement(
                xmlns + "Image",
                new XAttribute("height", 16),
                new XAttribute("width", 16),
                new XAttribute("type", "image/x-icon"),
                String.Format("http://{0}/favicon.ico", domain))));
    return doc.ToString(); // If you _must_ have a string
}
Run Code Online (Sandbox Code Playgroud)

  • 好的.我想我已经在这8个答案和所有评论之间找到了答案.这就是我的计划:重构一下并使用Jim Schubert的代码.然而,这绝对是答案,因为我认为在其他情况下,你是绝对正确的.但是,我并不担心"域"的价值,我已经验证了XML,这是一个几乎肯定不会在结构上改变的文件.如果确实如此,那就是当我重构它以使用XmlWriter时,因为这证明它比我想象的更流畅. (2认同)