4

An instance of System.Xml.XmlWriter is writing to an underlying Stream right ?(regardless of what the specific implementation of the XmlWriter is)

So how come there are no methods available for a programmer to retrieve the Stream object from the XmlWriter?

I'm sure I am missing something simple. Thanks in advance.

PS: In case anyone asks, what I really want to do is get the stream from an XmlWriter instance passed to me, and create an XmlReader from it (flush the Writer first if needs be).

I then need to use the XmlReader as a parameter to XslCompiledTransform.Transform method

Edit: punctuation

K_M
  • 43
  • 1
  • 4

1 Answers1

6

You should not do it. Even though you know that XmlWriter has some Stream underneath but this is implementation detail and XmlWriter should not give it to you. Also stream may readonly or writeonly, how will you read from it?

You should pass original stream that was used to instantiate XmlWriter to the place where you want to read the stream if you know that stream can be both written and read. Otherwise you should create a new stream which will read the content written by XmlWriter.

Snowbear
  • 16,924
  • 3
  • 43
  • 67
  • > You should not do it. It seems I cant anyway. But your explanation makes sense: There is no guarantee the stream can be read from. Thanks for that. > Otherwise you should create a new stream which will read the content written by XmlWriter. I am still struggling with how to do this though? – K_M Mar 30 '11 at 13:00
  • @K_M, it depends on how do you create that stream for `XmlWriter` - this is the key point here. – Snowbear Mar 30 '11 at 13:13
  • JIM-compiler, I am passed an instance of XmlWriter and so I will not know in advance how the Stream was created. Perhaps the design is flawed. But just so I get it straight - it is not possible to get a Stream (new or otherwise) from just an XmlWriter then? Which means, given an XmlWriter, there is no way to create an XmlReader with the same data? (Sorry I am going off topic. Let me know if its against the etquette here at stackoverflow). Thanks for your replies so far. – K_M Mar 30 '11 at 13:47
  • @K_M, do not think it is that much an off-topic. You can try casting passed `XmlWriter` to its real implementation class (`XmlWriter` is abstract), you will have to know what implementations of `XmlWriter` may be passed to you. Some `XmlWriter` inheritors, for example `XmlTextWriter`, expose passed stream (`XmlTextWriter.BaseStream` property), you can try it, I haven't tried. This will be a major hack, but if you really need it... – Snowbear Mar 30 '11 at 14:11
  • JIM-compiler, It makes sense for me to only accept XmlTextWriter rather than it's baseclass XmlWriter. From there I am able to use the BaseStream property, and create a new XmlReader from it. Problem solved. Thanks! – K_M Mar 30 '11 at 14:22