The following code doesn't work; the exception message reads "Root element is missing.":
MemoryStream transformed = new MemoryStream();
XmlDocument doc = new XmlDocument();
XmlReader input = null;
XslCompiledTransform xslt = new XslCompiledTransform();
input = XmlReader.Create("Example.xml");
xslt.Load("Example.xslt");
xslt.Transform(input, new XsltArgumentList(), transformed);
try {
doc.Load(transformed);
} catch (Exception ex) {
Console.WriteLine("XmlDocument.Load failed: {0}", ex.Message);
}
Console.ReadLine();
It isn't a problem with the input file or the transform script. The problem is that the XslCompiledTransform.Transform function leaves the stream position set to the end of the stream. There's no root element because the XmlDocument.Load function thinks the stream has a 0 byte length. The fix is to simply set the position to 0:
MemoryStream transformed = new MemoryStream();
XmlDocument doc = new XmlDocument();
XmlReader input = null;
XslCompiledTransform xslt = new XslCompiledTransform();
input = XmlReader.Create("Example.xml");
xslt.Load("Example.xslt");
xslt.Transform(input, new XsltArgumentList(), transformed);
// THE FIX
transformed.Position = 0;
try {
doc.Load(transformed);
} catch (Exception ex) {
Console.WriteLine("XmlDocument.Load failed: {0}", ex.Message);
}
Console.ReadLine();