在试图弄清楚如何将 .NET System.ServiceModel.Channels.Message 对象转换为 XmlDocument 时,我想我可以这样做:
Message message = Message.CreateMessage(messageVersion, "SOAPAction");
using(var messageBuffer = message.CreateBufferedCopy(int.MaxValue))
{
var stream = new MemoryStream();
using(var xmlWriter = XmlWriter.Create(stream))
{
var xmlDocument = new XmlDocument();
messageBuffer.WriteMessage(stream);
stream.Flush();
stream.Position = 0;
xmlDocument.Load(stream);
stream.Close();
Debug.Writeline(xmlDocument.OuterXml);
}
}
但是,这会导致 xmlDocument.Load(stream) 出现错误:
"Data at the root level is invalid. Line 1, position 1."
我现在意识到我应该将 Message 对象的 WriteMessage 与这样的 XmlWriter 对象结合使用:
Message message = Message.CreateMessage(messageVersion, "SOAPAction");
using(var messageBuffer = message.CreateBufferedCopy(int.MaxValue))
{
var stream = new MemoryStream();
using(var xmlWriter = XmlWriter.Create(stream))
{
var xmlDocument = new XmlDocument();
messageBuffer.CreateMessage().WriteMessage(xmlWriter);
xmlWriter.Flush();
stream.Flush();
stream.Position = 0;
xmlDocument.Load(stream);
xmlWriter.Close();
stream.Close();
Debug.WriteLine(xmlDocument.OuterXml);
}
}
我确定我错过了一些基本点,但这引出了我的问题 - MessageBuffer 对象上的 WriteMessage(Stream stream) 有什么用?