5

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • Mark - just occurred to me that I sometimes use a "stream inverter" for cases where some API wants to write to a stream and I need to read from it (i.e. for an ActionResult). This could be adapted to make a "text writer inverter", which would essentially give you true streamed access via `XDocument.Save`, but the downside is that it requires an extra thread to run. Would that help you here? – Aaronaught Apr 09 '10 at 17:23
  • @Aaronaught: Thanks, but that's probably too much to make of it. I mainly asked the question out of curiosity. In my current issue, I expect to be parsing a small piece of XML at application startup, so I can definitely live with loading the entire document at once. – Mark Seemann Apr 09 '10 at 17:26
  • Alrighty, I figured you were trying to send it over a network or something to that effect. I'm curious why you need to do this then, are you using an XML API that can only accept a `TextReader`? – Aaronaught Apr 10 '10 at 00:22
  • Yes, I'm implementing an interface that requires me to return a TextReader. – Mark Seemann Apr 10 '10 at 07:43

2 Answers2

5
  TextReader tr = new StringReader(xml.ToString());
halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel Elliott
  • 22,647
  • 10
  • 64
  • 82
  • Well, that's definitely better than my original approach, but still not really what I'm looking for (see my edited question). However, +1 one for giving me a one-line alternative :) – Mark Seemann Apr 09 '10 at 14:46
  • I would perhaps add that calling `TextReader` should be wrapped with `using` since it implements `IDisposable`. – Dan Atkinson May 27 '16 at 11:26
0

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.

Sven Künzler
  • 1,650
  • 1
  • 20
  • 22