Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML file loaded as a string

Tags:

c#

I have noticed some code that I wrote a few years back and whilst thinking about optimizations I thought that this maybe 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 could be very large as the number of products in a database increase, I am wondering if there is a better way to do this.

JD

like image 319
JD. Avatar asked Feb 09 '26 16:02

JD.


1 Answers

I would use Linq to XML link

You could 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());

outputs like this

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

This mean you are no mucking around with Strings.

Cheers

Iain

like image 108
Iain Avatar answered Feb 13 '26 15:02

Iain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!