I would really appreciate input on the following implementation. Goals are: produce an XElement, avoid file system reads/writes as much as possble.
private XElement ProduceApiXml(KeyValuePair<string, ConfigScriptOutput> kvp)
{
XElement returnValue = null;
// load xsl file
XslCompiledTransform ct = new XslCompiledTransform();
string xslFile = Path.Combine(_assemblyDir, ConfigurationManager.AppSettings["ConfigOutputXslFile"]);
ct.Load(xslFile);
XmlReader xmlToTransform = XmlReader.Create(new StringReader(kvp.Value.ScriptStdOut));
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlWriter xmlTransformed = new XmlTextWriter(sw);
ct.Transform(xmlToTransform, xmlTransformed);
returnValue = XElement.Parse(sb.ToString());
return returnValue;
}
This is the first time I have used this XslCompiledTransform class, and I am thinking I could imporve on it. My real concern is should I be using something other than the StringBuilder -> StringWriter -> XmlWriter constructs to get to where I want to be? Seems like a lot of objects built up to do the task at hand – which does work. Right now, working wins, but I want to make it better.
I’d really appreciate those of you with the experience commenting constructively on what I have done here. A code review, if you will?
Thanks in advance for your time.
If you want to populate an XElement then use
there is no need to use a StringWriter and no need to use the legacy XmlTextWriter, the transformation can directly populate an XContainer.
I would also wrap the use of XmlReader and StringReader into
usingblocks.