473,407 Members | 2,546 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

How to load an XmlTextReader from stream

I have an XML document in a file (e:\bobo.xml) saved using unicode
encoding with declaration:
<?xml version="1.0" encoding="UTF-16"?>

I can load that file into an XmlTextReader and read it just fine:
XmlTextReader reader = new XmlTextReader( @"e:\bobo.xml" );
reader.Read();

But this fails reporting, "This is an unexpected token. The expected
token is 'NAME'. Line 1, position 2.":
sr = new StreamReader( @"e:\bobo.xml" );
reader = new XmlTextReader( sr );
reader.Read();

Can anyone tell me why?
Nov 12 '05 #1
3 4527
Actually, this was simply because I should have used the overload of the
constructor that includes a parameter for encoding and it would work fine.

However, I don't know why this won't work:
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter( ms, Encoding.Unicode );
// this just reads with StreamReader and returns ReadToEnd()
string fileContents = FileUtils.fileToString(@"e:\bobo.xml");
bw.Write( fileContents );
reader = new XmlTextReader( ms );
reader.Read();

I thought that plain .net strings are encoded in unicode. The file is
encoded in unicode, the XML declaration includes 'encoding="utf-16"',
and the BinaryWriter is set to write unicode, so what is the problem?

Brad Wood wrote:
But this fails reporting, "This is an unexpected token. The expected
token is 'NAME'. Line 1, position 2.":
sr = new StreamReader( @"e:\bobo.xml" );
reader = new XmlTextReader( sr );
reader.Read();

Nov 12 '05 #2
"Brad Wood" <bradley|.wood|@ndsu|.edu> wrote in message news:uG**************@tk2msftngp13.phx.gbl...
I thought that plain .net strings are encoded in unicode. The file is encoded in unicode, the XML declaration includes
'encoding="utf-16"', and the BinaryWriter is set to write unicode, so what is the problem?


1. Make sure when you create the StreamReader in your fileToString( )
method that you use the overload that takes an encoding, and that you
are passing the same Encoding.Unicode (little-Endian, no BOM) to it.

2. After you call bw.Write( ) you should call bw.Flush( ). It may be
possible to get away with this on small-writes, but it can cause many
sleepless hours if you've written content that hasn't been committed
yet.

3. Normally, after you write to a MemoryStream the 'pointer' inside of
the MemoryStream will be resting at the end-of-the-Stream. This
requires you to reset the pointer back to the beginning-of-the-Stream
using either of:

ms.Seek( 0, SeekOrigin.Begin);

or alternately,

ms.Position = 0;

before you begin reading from it. The usual error for this mistake reads
to the effect, "There is no root element [at the end of your Stream!]"

4. However, # 3 has a wrinkle to it in your specific program because
you're using BinaryWriter.Write( string ), and that's a special method.
It's special because it always prefixes the string it writes out with the
string's Length. Therefore you're only receiving UTF-16 encoding
following that Length, however this is quite enough to throw off a
Unicode decoder. The usual error for this mistake reads to the
effect "There is invalid data at the root level. [First character!]"

So if fileContents.Length < 256 you want to reset the MemoryStream
to 1, and if it's between 256 and 65535 inclusive then you want to set it
to 2, etc., to cover the offset of the string length prefix Write( ) writes for
you. It has to put the string prefix there, btw, because that's how Read(
string) knows how far to go in a BinaryReader.
Derek Harmon
Nov 12 '05 #3
Sorry I took so long to check back. Your info is very good; explained
everything.

It does seem a bit strange to me, however, that the
BinaryWriter.Write( string )
adds the string length indicator to its MemoryStream, but calling
new StreamReader( @"e:\bobo.xml", Encoding.Unicode );
deosn't.
It would seem that if the BinaryWriter's MemoryStream needs to know the
length of its data, the StreamReader's would as well...

Derek Harmon wrote:
4. However, # 3 has a wrinkle to it in your specific program because
you're using BinaryWriter.Write( string ), and that's a special method.
It's special because it always prefixes the string it writes out with the
string's Length. Therefore you're only receiving UTF-16 encoding
following that Length, however this is quite enough to throw off a
Unicode decoder. The usual error for this mistake reads to the
effect "There is invalid data at the root level. [First character!]"

So if fileContents.Length < 256 you want to reset the MemoryStream
to 1, and if it's between 256 and 65535 inclusive then you want to set it
to 2, etc., to cover the offset of the string length prefix Write( ) writes for
you. It has to put the string prefix there, btw, because that's how Read(
string) knows how far to go in a BinaryReader.

Nov 12 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Tom Pearson | last post by:
I have created an XmlDocument and can see that this is correctly formed and has a root element If I Save the doc to a file and reload it all works o If I dump the doc to a stream, again using the...
1
by: Koji Ishii | last post by:
I'm trying to read response from a web server using XmlTextReader. Here's a code snippet. WebResponse rs = this.WebRequest.GetResponse(); Stream stm = rs.GetResponseStream(); XmlTextReader...
3
by: Emily John | last post by:
I am using xml serialization to generate my xml document. I am getting the data as stream of memory and then converting it to xml document object without saving it to the file system. How do I...
2
by: Yuriy | last post by:
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
2
by: ecomputerdelicacy | last post by:
Compact Framework SP3 (and I think also SP2 and SP1) XmlTextReader does not handle !DOCTYPE and (maybe?) rdf elements. How can I get the XmlTextReader to read these without issuing a...
3
by: Kjeld | last post by:
My scenario: I'm using an XmlTextReader to Deserialize serveral classes from a single xml document. Every class i pass the source stream, containing the xml. Each class subsequently creates an...
1
by: Borgbjerg | last post by:
I've got a multi-threaded server (we are very early in the project, trying to uncover some risks), and I want to send data using XML. The class ServerAdapter is supposed to connect to the server...
1
by: Nick | last post by:
Hi All, if i have the following code: StringReader stringReader = new StringReader(c_XML); XmlTextReader xmlReader = new XmlTextReader(stringReader); If I call 'xmlReader.Close();' I take it...
3
by: g66g08d14 | last post by:
Hi. We have a Jabber-esque client server package that uses XMPP for communication over network sockets. Using .NET 2.0, I need to read a full stanza (i.e. balanced xml) as soon as available...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.