473,371 Members | 1,753 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,371 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 4525
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.