문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top