元素不是类型的实例

时间:2013-02-19 10:52:50

标签: msmq linq-to-xsd

我正在使用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>

查看该行<{1}}的值

xml

我可以看到它生成了这个

var typedXML = XML.Parse(xml);

换句话说,它会在整个xml周围生成一个额外的xml节点。如果我在调试器中删除了这个额外的节点,那么一切正常。我做错了什么?

1 个答案:

答案 0 :(得分:1)

这是使用hte XmlMessageFormatter的结果,因为它序列化您的对象并将其包装在XML中。我建议您将XML文档直接写入BodyStream属性。

var msg = new Message();
var writer = new StreamWriter(msg.BodyStream);

writer.Write(xmlDoc.ToString());
writer.Flush();

queue.Send(msg);

这样您就可以完全控制队列中发送的内容。格式化程序主要用于遗留用途,在将XML文档作为消息发送时不应使用。