What's so bad about building XML with string concatenation?

前端 未结 12 1391
长发绾君心
长发绾君心 2020-12-01 12:21

In the thread What’s your favorite “programmer ignorance” pet peeve?, the following answer appears, with a large amount of upvotes:

Programmers who build XML u

12条回答
  •  执念已碎
    2020-12-01 13:05

    I think readability, flexibility and scalability are important factors. Consider the following piece of Linq-to-Xml:

    XDocument doc = new XDocument(new XDeclaration("1.0","UTF-8","yes"),
       new XElement("products", from p in collection
        select new XElement("product",
            new XAttribute("guid", p.ProductId), 
            new XAttribute("title", p.Title),
            new XAttribute("version", p.Version))));
    

    Can you find a way to do it easier than this? I can output it to a browser, save it to a document, add attributes/elements in seconds and so on ... just by adding couple lines of code. I can do practically everything with it without much of effort.

提交回复
热议问题