Question

I have an XslCompiledTransform object, and I want the output in an XmlReader object, as I need to pass it through a second stylesheet. I'm getting a bit confused - I can successfully transform some XML and read it using either a StreamReader or an XmlDocument, but when I try an XmlReader, I get nothing.

In the example below, stylesheet is my XslCompiledTransform object. The first two Console.WriteLine calls output the correct transformed XML, but the third call gives no XML. I'm guessing it might be that the XmlTextReader is expecting text, so maybe I need to wrap this in a StreamReader..? What am I doing wrong?

MemoryStream transformed = new MemoryStream();
stylesheet.Transform(input, args, transformed);
transformed.Position = 0;

StreamReader s = new StreamReader(transformed);
Console.WriteLine("s = " + s.ReadToEnd()); // writes XML
transformed.Position = 0;

XmlDocument doc = new XmlDocument();
doc.Load(transformed);
Console.WriteLine("doc = " + doc.OuterXml); // writes XML
transformed.Position = 0;

XmlReader reader = new XmlTextReader(transformed);
Console.WriteLine("reader = " + reader.ReadOuterXml()); // no XML written
Was it helpful?

Solution

The XmlReader.ReadOuterXml method reads the XML for the current node. When you first create the reader, there is no current node, so ReadOuterXml will return nothing.

If you add the line:

reader.Read();

...before the ReadOuterXml() call, then it will work as you expect.

P.S. You should normally test the result of the Read() method to ensure that the reader actually has something to read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top