Groups | Blog | Home
all groups > dotnet xml > january 2004 >

dotnet xml : Error: There is no Unicode byte order mark. Cannot switch to Unicode


Jim P.
1/29/2004 9:22:21 PM
I have a client server set of apps that can connect through socets and send
data back and forth. I'm trying to get it to send XML messages back and
both. Currently it works as string data. I collect all of the incoming data
to a string but when I try to parse the incoming XML I get the following
message:

-------------------------------------------
Error Parsing message: System.Xml.Exception: There is no Unicode byte order
mark. Cannot switch to unicode.
-------------------------------------------

I use XmlTextWriter and build it into a StringWriter. The StringWriter
encodes into UTF-16 instead of UTF-8, so I'm not if this is the problem. I
convert the StringWriter into a string which I then send across the wire to
the server. The server recieves the data with no problem and use a
StringBuilder to collect it. I conver the StringBuilder to a string. The
string is given to a parseMessage() class which encodes
(System.Text.Encoding.ASCII.GetBytes) the string into a Stream. The Stream
is then read in the XmlTextReader where it throws the exception.

// *********** CLASS TO WRITE XML **************
public string writePeerAdv(string type, string command)
{
// StringWriter to write to
StringWriter sw = new StringWriter();

// Create XmlTextWriter object
XmlTextWriter writer = new XmlTextWriter(sw);

// Begin Document
writer.WriteStartDocument();
writer.Formatting = Formatting.Indented;
// Write the file
writer.WriteStartElement("Message");
writer.WriteElementString("Type", type);
writer.WriteElementString("Command", command);
writer.WriteEndElement();
// Close Document
writer.Close();

// Return string
string peerAdv = sw.ToString();
return peerAdv;
}
// ************************************************


// ******* CLASS TO PARSE XML *******************
public void parseMessage(string incomingMessage)
{
// Create Strem to read from
Stream stream = new
MemoryStream(System.Text.Encoding.ASCII.GetBytes(incomingMessage));

// Read the stream into XmlTextReader
XmlTextReader reader = new XmlTextReader(stream);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
MessageBox.Show("Found an Element: " + reader.Value.ToString());
}
}
// Close the stream
reader.Close();
}
// ************************************************

Any ideas? Thanks for the help,
Jim

Daniel Cazzulino
1/30/2004 3:31:22 PM
There's no need to use GetBytes. In fact, that may cause you some problems
if non-ASCII information comes with the string, which is always Unicode in
..NET.
You should use a StringReader instead, and pass it directly to the
XmlTextReader ctor:

XmlTextReader tr = new XmlTextReader(new StringReader( incomingMessage ) );


HTH

--
Daniel Cazzulino
Lagash Systems SA
http://weblogs.asp.net/cazzu

[quoted text, click to view]

AddThis Social Bookmark Button