我正在使用 Linq To XSD 通过 MSMQ 发送数据。这是我的发送代码
public void Send()
{
string criMessageQueuePath = ConfigurationManager.AppSettings["CRIMessageQueuePath"];
if (!MessageQueue.Exists(criMessageQueuePath))
{
MessageQueue.Create(criMessageQueuePath, false);
}
var messageQueue = new MessageQueue(criMessageQueuePath) { Label = "CRI Message Queue" };
messageQueue.Formatter = new XmlMessageFormatter(new[] { typeof(XML) });
var transaction = new MessageQueueTransaction();
transaction.Begin();
messageQueue.Send(CreateAuction(1), transaction);
messageQueue.Send(CreateAuction(2), transaction);
messageQueue.Send(CreateAuction(3), transaction);
messageQueue.Send(CreateAuction(4), transaction);
messageQueue.Send(CreateAuction(5), transaction);
transaction.Commit();
}
private XML CreateAuction(int id)
{
var message = new XML {id = id};
return message;
}
这是我的接收代码
public IEnumerable<string> Receive()
{
string criMessageQueuePath = ConfigurationManager.AppSettings["CRIMessageQueuePath"];
var messageQueue = new MessageQueue(criMessageQueuePath);
Message[] messages = messageQueue.GetAllMessages();
foreach (Message message in messages)
{
message.Formatter = new XmlMessageFormatter(new[] { typeof(XML) });
yield return message.Body.ToString();
}
messageQueue.Purge();
}
我已经尝试了很多此代码的变体,但无法弄清楚为什么我无法从另一端获取有效的 XML 对象。
目前,当我调用它时,我的代码失败了
static void Main()
{
var sender = new Sender.Sender();
sender.Send();
var receiver = new Receiver.Receiver();
foreach (var xml in receiver.Receive())
{
var typedXML = XML.Parse(xml);
Console.WriteLine(typedXML.id);
}
}
它失败的那一行是var typedXML = XML.Parse(xml);
. 错误是
Element is not an instance of type Domain.XML
对象的 XSD 是
<?xml version="1.0" encoding="Windows-1252"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="Domain">
<xs:element name="XML">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
看值xml
就行
var typedXML = XML.Parse(xml);
我可以看到它生成了这个
"<XML>\r\n <XML xmlns=\"Domain\">\r\n <id>1</id>\r\n </XML>\r\n</XML>"
换句话说,它会围绕整个 xml 生成一个额外的 xml 节点。如果我在调试器中删除这个额外的节点,那么一切正常。我究竟做错了什么?