如何将 XslCompiledTransform 的输出获取到 XmlReader 中?
我有一个 XslCompiledTransform
对象,并且我希望将输出保存在 XmlReader
对象中,因为我需要将其传递到第二个样式表。我有点困惑 - 我可以成功转换一些 XML 并使用 StreamReader
或 XmlDocument
读取它,但是当我尝试 XmlReader
代码>,我什么也没得到。
在下面的示例中,stylesheet
是我的 XslCompiledTransform
对象。前两个 Console.WriteLine
调用输出正确的转换后的 XML,但第三个调用没有给出 XML。我猜测 XmlTextReader 可能需要文本,所以也许我需要将其包装在 StreamReader 中......?我做错了什么?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
XmlReader.ReadOuterXml
< /a> 方法读取当前节点的 XML。当您第一次创建读取器时,没有当前节点,因此 ReadOuterXml 不会返回任何内容。如果您在
ReadOuterXml()
调用之前添加以下行:...,那么它将按您的预期工作。
PS 您通常应该测试
Read()
方法的结果,以确保读者确实有东西要读。The
XmlReader.ReadOuterXml
method reads the XML for the current node. When you first create the reader, there is no current node, soReadOuterXml
will return nothing.If you add the line:
...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.