XML file loaded as a string
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
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
The idiomatic way to represent that piece of code using LINQ to XML would look more like this:
var element = new XElement("products",
products.Select(p => XElement.Parse(p.AsXml())));
return element.ToString();
Though it is better suited for situations where you can represent the XML in memory. If not, I believe your best option is to use an XmlWriter.
精彩评论