Groups | Blog | Home
all groups > dotnet xml > february 2005 >

dotnet xml : XmlTextReader and xml fragment



Yuriy
2/11/2005 10:07:24 AM
Hi,

any ideas how to read XML fragment from TextReader? XmlTextReader constructor
accepts only Stream or string as source Do I miss something?

thanks
Yuriy

Derek Harmon
2/12/2005 9:51:08 PM
[quoted text, click to view]

You've missed the constructor that takes a TextReader. You would use the
XmlTextReader( string, ...) constructor if the XML is in a file or at some URL.
You would wrap a string containing an XML fragment in a StringReader (which
IS-A TextReader) and pass that to the XmlTextReader( TextReader, ...) con-
structor.

Herein really lies your solution. Put the XML fragment into a string, and wrap
it in a System.IO.StringReader. Pass that to the TextReader-accepting con-
structor of XmlTextReader.

There's a caveat to be aware of. If the fragment contains multiple top-level
elements, then you must make XmlTextReader believe it is a document with
a single root element.

The easiest way to do this is to wrap these top-level elements as a group in
a single "make-believe" root element so that it appears to XmlTextReader
as a document, and compensate for this artificial container element when
doing your XML processing.

// . . .
xmlFragmentStr = string.Format("<root>{0}</root>", xmlFragmentStr);
StringReader readerSource = new StringReader( xmlFragmentStr);
XmlTextReader reader = new XmlTextReader( readerSource);
// . . .


Derek Harmon

Yuriy Solodkyy
2/14/2005 12:58:13 AM
Hi,

it is not suitable for large XML fragments. I have already implemented a
wrapper that
does what I need, but it is interesting why TextReader is not considered
as a source of
by .NET framework in this case. I allow that Stream choice can be ommited,
because it
is easely wrapped into TextReader.

Anyway thank you for answer

[quoted text, click to view]


AddThis Social Bookmark Button