views:

111

answers:

2

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.

+1  A: 
  TextReader tr = new StringReader(xml.ToString());

Kindness,

Dan

Daniel Elliott
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
A: 

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
Yes, but that's the rub. Unless I'm missing something, there's no easy conversion from XmlReader to TextReader.
Mark Seemann