XmlMessageFormatter XmlMessageFormatter XmlMessageFormatter XmlMessageFormatter Class

定義

使用根據 XSD 結構描述定義的 XML 格式,將物件序列化為訊息主體,或從訊息主體還原序列化為物件。Serializes and deserializes objects to or from the body of a message, using the XML format based on the XSD schema definition.

public ref class XmlMessageFormatter : ICloneable, System::Messaging::IMessageFormatter
public class XmlMessageFormatter : ICloneable, System.Messaging.IMessageFormatter
type XmlMessageFormatter = class
    interface IMessageFormatter
    interface ICloneable
Public Class XmlMessageFormatter
Implements ICloneable, IMessageFormatter
繼承
XmlMessageFormatterXmlMessageFormatterXmlMessageFormatterXmlMessageFormatter
實作

範例

下列程式碼範例包含三段程式碼: 伺服器元件、順序類別和用戶端程式代碼。The following code example includes three pieces of code: a server component, an order class, and client code. XSD.EXE 公用程式可使用 order 類別來產生伺服器在傳入訊息內辨識的架構。The order class can be used by the XSD.exe utility to generate schema that the server recognizes within incoming messages. 架構是 XML 格式的檔案, 可描述類別的「圖形」。The schema is an XML formatted file that describes the "shape" of the class. 接著, 您可以在用戶端上使用此架構來產生用戶端特定的 order 類別, 該類別會共用與伺服器類別相同的架構。This schema can then be used on the client side to generate a client-specific order class that shares the same schema as the server class.

下列程式碼範例代表透過訊息佇列接收訂單的伺服器元件。The following code example represents a server component that receives orders through a message queue. 訊息的主體應為 order 物件, 其架構符合下列 Order.cs 類別。The body of the message should be an order object whose schema matches the Order.cs class below. 伺服器進程或應用程式會還原序列化順序。The server process or application deserializes the order.

#using <System.dll>
#using <System.Messaging.dll>

using namespace System;
using namespace System::Messaging;

// placeholder; see complete definition elsewhere in this section
public ref class Order
{
public:
   void ShipItems(){}

};


// Creates the queue if it does not already exist.
void EnsureQueueExists( String^ path )
{
   if (  !MessageQueue::Exists( path ) )
   {
      MessageQueue::Create( path );
   }
}

int main()
{
   Console::WriteLine( "Processing Orders" );
   String^ queuePath = ".\\orders";
   EnsureQueueExists( queuePath );
   MessageQueue^ queue = gcnew MessageQueue( queuePath );
   array<String^>^temp0 = {"Order"};
   (dynamic_cast<XmlMessageFormatter^>(queue->Formatter))->TargetTypeNames = temp0;
   while ( true )
   {
      Order^ newOrder = dynamic_cast<Order^>(queue->Receive()->Body);
      newOrder->ShipItems();
   }
}

using System;
using System.Messaging;
 
 public class Server{
 
     public static void Main(){
 
         Console.WriteLine("Processing Orders");
 
         string queuePath = ".\\orders";
         EnsureQueueExists(queuePath);
         MessageQueue queue = new MessageQueue(queuePath);
         ((XmlMessageFormatter)queue.Formatter).TargetTypeNames = new string[]{"Order"};
 
         while(true){
             Order newOrder = (Order)queue.Receive().Body;
             newOrder.ShipItems();
         }
     }
 
     // Creates the queue if it does not already exist.
     public static void EnsureQueueExists(string path){
         if(!MessageQueue.Exists(path)){
             MessageQueue.Create(path);
         }
     }
 }
Imports System.Messaging



Public Class Server
    
    
    Public Shared Sub Main()
        
        Console.WriteLine("Processing Orders")
        
        Dim queuePath As String = ".\orders"
        EnsureQueueExists(queuePath)
        Dim queue As New MessageQueue(queuePath)
        CType(queue.Formatter, XmlMessageFormatter).TargetTypeNames = New String() {"Order"}
        
        While True
            Dim newOrder As Order = CType(queue.Receive().Body, Order)
            newOrder.ShipItems()
        End While
    End Sub
    
    
    ' Creates the queue if it does not already exist.
    Public Shared Sub EnsureQueueExists(path As String)
        If Not MessageQueue.Exists(path) Then
            MessageQueue.Create(path)
        End If
    End Sub
End Class

下列程式碼範例所表示的 order 類別, 會為伺服器上的應用程式所接收和還原序列化的順序物件提供架構。The following code example represents the order class that provides a schema for the order objects that the application on the server receives and deserializes.

using namespace System;
public ref class Order
{
public:
   int itemId;
   int quantity;
   String^ address;
   void ShipItems()
   {
      Console::WriteLine( "Order Placed:" );
      Console::WriteLine( "\tItem ID  : {0}", itemId );
      Console::WriteLine( "\tQuantity : {0}", quantity );
      Console::WriteLine( "\tShip To  : {0}", address );
      
      // Add order to the database.
      /* Insert code here. */
   }

};

using System;
 
 public class Order{
 
     public int itemId;
     public int quantity;
     public string address;
 
     public void ShipItems(){
 
         Console.WriteLine("Order Placed:");
         Console.WriteLine("\tItem ID  : {0}",itemId);
         Console.WriteLine("\tQuantity : {0}",quantity);
         Console.WriteLine("\tShip To  : {0}",address);
 
         // Add order to the database.
         /* Insert code here. */
 
     }
 }
Public Class Order
    
    Public itemId As Integer
    Public quantity As Integer
    Public address As String
    
    
    Public Sub ShipItems()
        
        Console.WriteLine("Order Placed:")
        Console.WriteLine(ControlChars.Tab & "Item ID  : {0}", itemId)
        Console.WriteLine(ControlChars.Tab & "Quantity : {0}", quantity)
        Console.WriteLine(ControlChars.Tab & "Ship To  : {0}", address)

        ' Add order to the database.
        ' Insert code here.
 
    End Sub
End Class

任何與伺服器上應用程式互動的用戶端應用程式, 都必須將本機定義之 order 類別中的資訊序列化為訊息本文, 以將訊息傳送至伺服器。Any client application that interacts with the application on the server must send messages to the server by serializing information in a locally defined order class into the message body. 本機定義的順序類別必須與伺服器定義的順序類別具有相同的架構, 伺服器上的應用程式會嘗試將訊息本文還原序列化。The locally defined order class must have the same schema as the server-defined order class into which the application on the server will attempt to deserialize the message body. XSD.EXE 公用程式可讓伺服器上的應用程式管理員建立和散發用戶端必須用來序列化傳送至伺服器之訊息的架構。The XSD.exe utility lets the manager of the application on the server create and distribute the schema the client must use to serialize messages going to the server.

當用戶端應用程式的管理員收到 order 類別的架構時, 會再次使用 XSD.EXE 公用程式從架構產生用戶端特定的 order 類別。When the manager of the client application receives the schema for the order class, the XSD.exe utility is used again to generate a client-specific order class from the schema. 這是在下列用戶端程式代碼範例中使用的這個類別, 而不是伺服器的 order 類別 (XSD.EXE 公用程式會導致架構產生的類別與原始類別具有相同的名稱)。It is this class that is used in the client code example below, not the server's order class (the XSD.exe utility causes the schema-generated class to have the same name as the original class). 這個新的 order 類別是用來將順序序列化為訊息內文。This new order class is used to serialize the order into the message body.

下列程式碼範例是用戶端處理, 用來序列化訂單並將與訂單相關聯的資訊傳送至佇列。The following code example is the client-side processing, used to serialize an order and send the information associated with the order to a queue. 此程式碼會將專案、數量和位址資訊與 XSD.EXE 公用程式為 Order.cs 類別所產生之架構的元素建立關聯。The code associates Item, Quantity, and Address information with elements of the schema that were generated for the Order.cs class by the XSD.exe utility. 訂單會傳送到本機電腦上的 Orders 佇列。An order is sent to the Orders queue on the local computer.

#using <System.dll>
#using <System.Messaging.dll>

using namespace System;
using namespace System::Messaging;

// placeholder; see complete definition elsewhere in this section
public ref class Order
{
public:
   int itemId;
   int quantity;
   String^ address;
   void ShipItems(){}

};


// Creates the queue if it does not already exist.
void EnsureQueueExists( String^ path )
{
   if (  !MessageQueue::Exists( path ) )
   {
      MessageQueue::Create( path );
   }
}

int main()
{
   String^ queuePath = ".\\orders";
   EnsureQueueExists( queuePath );
   MessageQueue^ queue = gcnew MessageQueue( queuePath );
   Order^ orderRequest = gcnew Order;
   orderRequest->itemId = 1025;
   orderRequest->quantity = 5;
   orderRequest->address = "One Microsoft Way";
   queue->Send( orderRequest );
   
   // This line uses a new method you define on the Order class:
   // orderRequest.PrintReceipt();
}

using System;
using System.Messaging;
 
 class Client{
 
     public static void Main(){
 
         string queuePath = ".\\orders";
         EnsureQueueExists(queuePath);
         MessageQueue queue = new MessageQueue(queuePath);
 
         Order orderRequest = new Order();
         orderRequest.itemId = 1025;
         orderRequest.quantity = 5;
         orderRequest.address = "One Microsoft Way";
 
         queue.Send(orderRequest);
         // This line uses a new method you define on the Order class:
         // orderRequest.PrintReceipt();
     }
 
     // Creates the queue if it does not already exist.
     public static void EnsureQueueExists(string path){
         if(!MessageQueue.Exists(path)){
             MessageQueue.Create(path);
         }
     }
 
 }
Imports System.Messaging

Class Client
    
    
    Public Shared Sub Main()
        
        Dim queuePath As String = ".\orders"
        EnsureQueueExists(queuePath)
        Dim queue As New MessageQueue(queuePath)
        
        Dim orderRequest As New Order()
        orderRequest.itemId = 1025
        orderRequest.quantity = 5
        orderRequest.address = "One Microsoft Way"
        
        queue.Send(orderRequest)
        ' This line uses a new method you define on the Order class:
        ' orderRequest.PrintReceipt()

    End Sub
    
    ' Creates the queue if it does not already exist.
    Public Shared Sub EnsureQueueExists(path As String)
        If Not MessageQueue.Exists(path) Then
            MessageQueue.Create(path)
        End If
    End Sub
End Class

在伺服器上從 order 類別產生架構之後, 您就可以修改類別。After the schema is generated from the order class on the server, you can modify the class. 除非架構變更, 否則您不需要轉散發架構。Unless the schema changes, you do not need to redistribute the schema. 當您散發架構並產生用戶端順序類別之後, 只要架構本身並未修改, 該用戶端類別也可以與伺服器的 order 類別分開修改。After you have distributed the schema and generated a client-side order class, that client class can also be modified independently of the server's order class, as long as the schema itself is not modified. 這兩個類別已變得鬆散結合。The two classes have become loosely coupled.

備註

XmlMessageFormatterMessageQueue實例用來序列化寫入佇列之訊息的預設格式器。The XmlMessageFormatter is the default formatter that an instance of MessageQueue uses to serialize messages written to the queue. 當您建立的實例MessageQueue時, XmlMessageFormatter會為MessageQueue您建立的實例, 並與相關聯。When you create an instance of MessageQueue, an instance of XmlMessageFormatter is created for you and associated with the MessageQueue. 您可以指定不同的格式器, 方法是在程式碼中建立它, Formatter並將它MessageQueue指派給的屬性。You can specify a different formatter by creating it in your code and assigning it to the Formatter property of your MessageQueue.

佇列的預設XmlMessageFormatter實例可以用來寫入佇列, 但它無法用來從佇列讀取, 直到您在格式器上設定TargetTypesTargetTypeNames屬性為止。A queue's default XmlMessageFormatter instance can be used to write to the queue, but it cannot be used to read from the queue until you set either the TargetTypes or TargetTypeNames property on the formatter. 您可以在預設的格式器實例上設定其中一個或兩個值, 也可以建立格式器的新實例, 並藉由將它們當做引數傳遞至適當XmlMessageFormatter的函式來自動設定值。You can either set one or both of these values on the default formatter instance, or you can create a new instance of the formatter and set the values automatically by passing them as arguments into the appropriate XmlMessageFormatter constructor.

當指定TargetTypes TargetTypeNames而不是時, 會在編譯時期 (而不是讀取時間) 檢查類型存在, 以降低發生錯誤的可能性。When specifying TargetTypes rather than TargetTypeNames, type existence is checked at compile time rather than read time, reducing possibility for error. TargetTypeNames要求每個專案都必須是完整的, 並指定其元件名稱。TargetTypeNames requires every entry to be fully qualified, specifying its assembly name. 此外, 在使用多個並行版本時, 也必須將版本號碼附加至目標型別名稱。Further, when working with multiple concurrent versions, the version number must also be appended to the target type name as well.

TargetTypeNamesTargetTypes屬性會告知格式器在還原序列化訊息時, 要嘗試比對的架構。The TargetTypeNames and TargetTypes properties tell the formatter what schemas to attempt to match when deserializing a message. 這可讓格式器解讀訊息本文。This allows the formatter to interpret the message body.

在訊息本文中序列化的實例必須符合類型陣列中所表示的其中一個架構。The instance serialized in the message body must comply with one of the schemas represented in the type array. 當您使用Receive方法讀取訊息時, 方法會建立對應至所識別架構之類型的物件, 並將訊息本文讀入其中。When you read the message using the Receive method, the method creates an object of the type that corresponds to the schema identified and reads the message body into it.

從佇列讀取時, 只需要設定這兩個屬性的其中一個, 但您可以同時設定這兩者。Only one of the two properties needs to be set when reading from the queue, but you can set both. 這組類型是來自兩個屬性的組合集合。The set of types is the combined set from the two properties. 決定要使用哪一個屬性是您的應用程式特有的。The decision of which property to use is specific to your application. 如果訊息內文包含的類型, 其架構不符合任何一個屬性的陣列中的任何類型, 則在讀取訊息時就會擲回例外狀況。If the message body contains a type whose schema does not match any of the types in the array for either property, an exception will be thrown when the message is read.

XmlMessageFormatter是鬆散結合的 XML 訊息的重要元件。The XmlMessageFormatter is a crucial component of loosely coupled XML-based messaging. XSD.EXE 公用程式會使用 XML 格式來產生 XML 架構, 例如當您使用公用程式來序列化應用程式所使用的類別時。The XSD.exe utility uses the XML format is used to generate XML schema, such as when you use the utility to serialize a class used by your application. 類別必須有無參數建構函式。The class must have a parameterless constructor.

當公用程式根據您散發用來描述類別資料的架構產生類別時, 會在反向進程中再次使用此格式。The format is used again in the reverse process when the utility generates a class based on the schema you distribute to describe your class data. 使用公用程式和它所產生的 XML 架構, 可讓您在類別的實作變更之後, 每次重新編譯類別時, 都避免轉散發 .dll 檔案。The use of the utility and the XML schema it generates enables you to avoid redistributing.dll files every time you recompile a class after the implementation of your class has changed. 只要架構不會在用戶端或伺服器上變更, 任何一邊的其他變更就不會影響另一端。As long as the schema does not change on the client or the server, other changes on either side do not affect the other.

建構函式

XmlMessageFormatter() XmlMessageFormatter() XmlMessageFormatter() XmlMessageFormatter()

不使用目標型別 (Target Type) 集來初始化 XmlMessageFormatter 類別的新執行個體。Initializes a new instance of the XmlMessageFormatter class, without target types set.

XmlMessageFormatter(String[]) XmlMessageFormatter(String[]) XmlMessageFormatter(String[]) XmlMessageFormatter(String[])

初始化 XmlMessageFormatter 類別的新執行個體,將傳入的目標型別設定為 (完整的) 字串值陣列。Initializes a new instance of the XmlMessageFormatter class, setting target types passed in as an array of (fully qualified) string values.

XmlMessageFormatter(Type[]) XmlMessageFormatter(Type[]) XmlMessageFormatter(Type[]) XmlMessageFormatter(Type[])

初始化 XmlMessageFormatter 類別的新執行個體,將傳入的目標型別設定為物件型別的陣列。Initializes a new instance of the XmlMessageFormatter class, setting target types passed in as an array of object types.

屬性

TargetTypeNames TargetTypeNames TargetTypeNames TargetTypeNames

指定可能型別的設定,格式子會從所提供的訊息還原序列化這些型別。Specifies the set of possible types that will be deserialized by the formatter from the message provided.

TargetTypes TargetTypes TargetTypes TargetTypes

指定可能型別的設定,格式子會從所提供的訊息還原序列化這些型別。Specifies the set of possible types that will be deserialized by the formatter from the message provided.

方法

CanRead(Message) CanRead(Message) CanRead(Message) CanRead(Message)

決定格式子是否能夠還原序列化訊息。Determines whether the formatter can deserialize the message.

Clone() Clone() Clone() Clone()

建立 XmlMessageFormatter 類別的執行個體,其讀取/寫入屬性 (目標型別集) 與目前的 XmlMessageFormatter 執行個體相同。Creates an instance of the XmlMessageFormatter class whose read/write properties (the sets of target types) are the same as the current XmlMessageFormatter instance.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
Read(Message) Read(Message) Read(Message) Read(Message)

讀取指定訊息的內容,並建立包含還原序列化訊息的物件。Reads the contents from the given message and creates an object that contains the deserialized message.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
Write(Message, Object) Write(Message, Object) Write(Message, Object) Write(Message, Object)

將物件序列化到訊息主體中。Serializes an object into the body of the message.

適用於

另請參閱