XML file loaded as a string

I noticed some code that I wrote several years ago, and thinking about optimization, I thought that this could be an area that could be improved. I have the following:

var xml = new StringBuilder("");
foreach (var product in products)
{
xml.Append(product.AsXML());  // gives an xml string.
}
return String.Format("<products>{0}</products>", xml);

The xml string can be very large as the number of products in the database increases, I wonder if there is a better way to do this.

Jd

+3
source share
2 answers

I would use Linq for XML link

You can try something like this:

    var prod = new List<string>();
    prod.Add("Apples");
    prod.Add("Oranges");
    var doc = new XElement("Product");
    foreach(String p in prod){


        doc.Add(new XElement("products", p));
    }

    Debug.WriteLine(doc.ToString());

is output as follows

<Product>
  <products>Apples</products>
  <products>Oranges</products>
</Product>

This means that you do not twitch with the Strings.

Greetings

Yane

+1
source

The idiomatic way of representing this part of the code using LINQ to XML would look something like this:

var element = new XElement("products",
                  products.Select(p => XElement.Parse(p.AsXml())));

return element.ToString();

, XML . , , - XmlWriter.

+1

All Articles