views:

41

answers:

1

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
+1  A: 

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.

Aaronaught
Ok, that kinda works. The XML in question contains the standard prolog, a root node and one child node. After one Read() still nothing is printed. If I do 2 calls to Read() before printing, I get the XML without the prolog. Why's this then?
Graham Clark
@Graham: I'm not sure what you mean by "prolog" - I assume you mean the declaration? Technically that directive is not part of the document, it's a header, so I can see why it wouldn't print. If you know the name of the root element then replace `Read()` with `ReadToFollowing("NameOfRootElement")`.
Aaronaught