如何轻松地从 XDocument 获取 TextReader?

发布于 2024-08-28 15:32:32 字数 447 浏览 8 评论 0原文

给定一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨与橙与城 2024-09-04 15:32:32
  TextReader tr = new StringReader(xml.ToString());
  TextReader tr = new StringReader(xml.ToString());
恋你朝朝暮暮 2024-09-04 15:32:32

我没有尝试过,但是有一个方法XNode.WriteTo(XmlWriter)。您可以向它传递一个 XmlTextWriter 来获取文本表示。这可能需要更多代码
来编写,但它应该按照您的要求更像“流式”:-)

[编辑:] 更简单:有一个方法 XNode.CreateReader() 为您提供一个 XmlReader< /代码>。您只需自己处理文本转换即可。

I haven't tried it, but there is a Method XNode.WriteTo(XmlWriter). You could pass it a XmlTextWriter to get a textual representation. This probably will take somewhat more code
to write, but it should be more "stream-like" as you requested :-)

[Edit:] Even easier: There's a method XNode.CreateReader() which gives you an XmlReader. You'll just have to handle the conversion to text yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文