I am trying to find the best solution to prevent us to allocate too much memory when building an Xml document. I have to construct a fairly large Xml with the less resource possible (the web service must be able to handle hundreds of calls per seconds). The structure of the Xml itself doesn’t change much, however the data consistently change. My current solution is XDocument and XElement (LINQ). Below is a quick sample of what I am doing today:
static Stream GetXml(string d1, string d2, string d3)
{
XElement x =
new XElement("myElement",
new XElement("myOtherElement1", d1),
new XElement("myOtherElement2", d2),
new XElement("myOtherElement3", d3));
// ... more XElement
// ... return Stream
}
When the Xml document becomes too large, instantiating an XDocument and many hundreds of XElement becomes very expensive and the number of calls per second drops. I am currently thinking of creating some sort of template engine that would simply stream the strings (XElement) without instantiating any objects. How would you do that? Is that the right thing to do?
static Stream GetXml(string d1, string d2, string d3)
{
const string xml = @"
<myElement>
<myOtherElement1>{0}</myOtherElement1>
<myOtherElement2>{1}</myOtherElement2>
<myOtherElement3>{2}</myOtherElement3>
</myElement>";
// What's the best way to {0}, {1}, {2} without allocating
// objects and using as little RAM as possible. I cannot
// use string.Format since it allocates strings.
StreamWriter sw = new StreamWriter(stream);
sw.Write(xml);
}