简体   繁体   English

通过MSMQ发送的XML消息不包含编码

[英]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. 我正在编写一个使用MSMQ的应用程序,并且遇到了一个与XML声明标记的编码属性有关的问题。

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: xdoc.OuterXml的控制台输出显示已包含编码:

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

But when I send the message over MSMQ, the encoding attribute gets removed. 但是,当我通过MSMQ发送消息时,编码属性将被删除。

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

What am I missing here? 我在这里想念什么?

You missed the note in the documentation of the XmlDeclaration. 你错过了音符的XmlDeclaration的文档。

Note: If the XmlDocument is saved to either a TextWriter or an XmlTextWriter, this encoding value is discarded. 注意:如果将XmlDocument保存到TextWriter或XmlTextWriter,则将放弃此编码值。 Instead, the encoding of the TextWriter or the XmlTextWriter is used. 而是使用TextWriter或XmlTextWriter的编码。 This ensures that the XML written out can be read back using the correct encoding. 这确保了可以使用正确的编码来读回写出的XML。

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");
}

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. 代替ASCII,它必须是Unicode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM