2013-02-19 64 views
1

類型的實例我正在使用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節點。如果我在調試器中刪除這個額外的節點,那麼它一切正常。我究竟做錯了什麼?

回答

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文檔作爲消息發送時使用。