如何轻松地从 XDocument 获取 TextReader?
给定一个 XDocument 实例,我如何轻松获取代表该实例的 TextReader?
我能想到的最好的办法是这样的(其中 xml
是一个 XDocument 实例):
var s = new MemoryStream();
var sw = new StreamWriter(s);
xml.Save(sw);
sw.Flush();
s.Position = 0;
TextReader tr = new StreamReader(s);
但是,这看起来有点笨拙,所以我想知道是否有更简单的方法?
编辑
上面的示例相当于将整个实例转换为 XML 字符串,然后基于该字符串创建一个 TextReader。
我只是想知道是否有一种比将整个内容读入内存更类似于流的方法。
Given an XDocument instance, how can I easily get a TextReader that represents that instance?
The best I've been able to come up with is something like this (where xml
is an XDocument instance):
var s = new MemoryStream();
var sw = new StreamWriter(s);
xml.Save(sw);
sw.Flush();
s.Position = 0;
TextReader tr = new StreamReader(s);
However, this seems a little clunky, so I was wondering if there's an easier way?
Edit
The above example is equivalent to converting the entire instance to an XML string and then create a TextReader over that string.
I was just wondering whether there's a more stream-like way to do it than reading the entire contents into memory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有尝试过,但是有一个方法
XNode.WriteTo(XmlWriter)
。您可以向它传递一个XmlTextWriter
来获取文本表示。这可能需要更多代码来编写,但它应该按照您的要求更像“流式”:-)
[编辑:] 更简单:有一个方法
XNode.CreateReader()
为您提供一个XmlReader< /代码>。您只需自己处理文本转换即可。
I haven't tried it, but there is a Method
XNode.WriteTo(XmlWriter)
. You could pass it aXmlTextWriter
to get a textual representation. This probably will take somewhat more codeto write, but it should be more "stream-like" as you requested :-)
[Edit:] Even easier: There's a method
XNode.CreateReader()
which gives you anXmlReader
. You'll just have to handle the conversion to text yourself.