fasih.rana
fasih.rana

Reputation: 1655

XML Message sent over MSMQ does not include encoding

I'm writing an application that uses MSMQ and I'm encountering a problem specifically to do with encoding attribute for the XML declaration tag.

I'm constructing the message as below:

string xmlmsg = reqText.Text;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(new StringReader(xmlmsg));

xdoc.InsertBefore(xdoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"), xdoc.DocumentElement);

Message _msg = new Message();

_msg.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(xdoc.OuterXml));
reqQueue.Send(_msg, "XML Request");

The console output of xdoc.OuterXml reveals that the encoding is included:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

But when I send the message over MSMQ, the encoding attribute gets removed.

<?xml version="1.0" standalone="yes"?>

What am I missing here?

Upvotes: 1

Views: 1428

Answers (2)

fasih.rana
fasih.rana

Reputation: 1655

Turns out the encoding was wrong. Here is the simplified code that actually worked:

        Message _msg = new Message
        {
            Formatter = new XmlMessageFormatter(),
            BodyStream = new MemoryStream(Encoding.Unicode.GetBytes(_xmlmsg))
        };
        reqQueue.Send(_msg, "XML Request");

Instead of ASCII, it needed to be Unicode.

Upvotes: 1

Jesse de Wit
Jesse de Wit

Reputation: 4177

You missed the note in the documentation of the XmlDeclaration.

Note: If the XmlDocument is saved to either a TextWriter or an XmlTextWriter, this encoding value is discarded. Instead, the encoding of the TextWriter or the XmlTextWriter is used. This ensures that the XML written out can be read back using the correct encoding.

Try this piece of code instead:

string xmlmsg = reqText.Text;
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xmlmsg);

using (Message _msg = new Message())
using (var memStream = new MemoryStream())
using (var writer = XmlWriter.Create(memStream))
{
     writer.WriteStartDocument(standalone: true);
     xdoc.WriteTo(writer);
     writer.Flush();
     memStream.Seek(0, SeekOrigin.Begin);

     _msg.BodyStream = memStream;
     reqQueue.Send(_msg, "XML Request");
}

Upvotes: 1

Related Questions