SoapElementAttribute SoapElementAttribute SoapElementAttribute SoapElementAttribute Class

Определение

Указывает, что данный общий член будет сериализован посредством XmlSerializer как кодированный XML-элемент SOAP.Specifies that the public member value be serialized by the XmlSerializer as an encoded SOAP XML element.

public ref class SoapElementAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue)]
public class SoapElementAttribute : Attribute
type SoapElementAttribute = class
    inherit Attribute
Public Class SoapElementAttribute
Inherits Attribute
Наследование
SoapElementAttributeSoapElementAttributeSoapElementAttributeSoapElementAttribute
Атрибуты

Примеры

В следующем примере сериализуется экземпляр класса с именем Transportation , который содержит поле с именем. VehicleThe following example serializes an instance of a class named Transportation that contains a field named Vehicle. SoapElementAttribute К полю применяется.A SoapElementAttribute is applied to the field. При сериализации поля имя XML-элемента — «Wheels», а не «Vehicle».When the field is serialized, the XML element name is "Wheels" instead of "Vehicle". SerializeOverride Метод создаетSoapElement и задает для свойства объекта значение .SoapElementAttribute SoapAttributes SoapElementAttributeThe SerializeOverride method creates a SoapElementAttribute and sets the SoapElement property of a SoapAttributes to the SoapElementAttribute. Добавляется в, который используется для создания XmlTypeMapping. SoapAttributeOverrides SoapAttributesThe SoapAttributes is added to a SoapAttributeOverrides that is used to create an XmlTypeMapping. Создается с помощью, а экземпляр Transportationкласса XmlTypeMappingсновасериализуется XmlSerializer .An XmlSerializer is constructed with the XmlTypeMapping, and an instance of the Transportation class is again serialized. SoapElementAttribute Поскольку используется для переопределения сериализации, созданное имя элемента XML теперь является "грузовиком" вместо "Wheels".Because the SoapElementAttribute is used to override the serialization, the generated XML element name is now "Truck" instead of "Wheels".

#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;
using namespace System::Collections;
using namespace System::Xml;
using namespace System::Text;
public ref class Thing
{
public:

   [SoapElement(IsNullable=true)]
   String^ ThingName;
};

public ref class Transportation
{
public:

   // The SoapElementAttribute specifies that the
   // generated XML element name will be S"Wheels"
   // instead of S"Vehicle".

   [SoapElement("Wheels")]
   String^ Vehicle;

   [SoapElement(DataType="dateTime")]
   DateTime CreationDate;

   [SoapElement(IsNullable=true)]
   Thing^ thing;
};

public ref class Test
{
public:

   // Return an XmlSerializer used for overriding.
   XmlSerializer^ CreateSoapOverrider()
   {
      // Create the SoapAttributes and SoapAttributeOverrides objects.
      SoapAttributes^ soapAttrs = gcnew SoapAttributes;
      SoapAttributeOverrides^ soapOverrides = gcnew SoapAttributeOverrides;

      // Create an SoapElementAttribute to the Vehicles property.
      SoapElementAttribute^ soapElement1 = gcnew SoapElementAttribute( "Truck" );

      // Set the SoapElement to the Object*.
      soapAttrs->SoapElement = soapElement1;

      // Add the SoapAttributes to the SoapAttributeOverrides,specifying the member to.
      soapOverrides->Add( Transportation::typeid, "Vehicle", soapAttrs );

      // Create the XmlSerializer, and return it.
      XmlTypeMapping^ myTypeMapping = (gcnew SoapReflectionImporter( soapOverrides ))->ImportTypeMapping( Transportation::typeid );
      return gcnew XmlSerializer( myTypeMapping );
   }

   void SerializeOverride( String^ filename )
   {
      // Create an XmlSerializer instance.
      XmlSerializer^ ser = CreateSoapOverrider();

      // Create the Object* and serialize it.
      Transportation^ myTransportation = gcnew Transportation;
      myTransportation->Vehicle = "MyCar";
      myTransportation->CreationDate = DateTime::Now;
      myTransportation->thing = gcnew Thing;
      XmlTextWriter^ writer = gcnew XmlTextWriter( filename,Encoding::UTF8 );
      writer->Formatting = Formatting::Indented;
      writer->WriteStartElement( "wrapper" );
      ser->Serialize( writer, myTransportation );
      writer->WriteEndElement();
      writer->Close();
   }

   void SerializeObject( String^ filename )
   {
      // Create an XmlSerializer instance.
      XmlSerializer^ ser = gcnew XmlSerializer( Transportation::typeid );
      Transportation^ myTransportation = gcnew Transportation;
      myTransportation->Vehicle = "MyCar";
      myTransportation->CreationDate = DateTime::Now;
      myTransportation->thing = gcnew Thing;
      XmlTextWriter^ writer = gcnew XmlTextWriter( filename,Encoding::UTF8 );
      writer->Formatting = Formatting::Indented;
      writer->WriteStartElement( "wrapper" );
      ser->Serialize( writer, myTransportation );
      writer->WriteEndElement();
      writer->Close();
   }
};

int main()
{
   Test^ t = gcnew Test;
   t->SerializeObject( "SoapElementOriginal.xml" );
   t->SerializeOverride( "SoapElementOverride.xml" );
   Console::WriteLine( "Finished writing two XML files." );
}
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
using System.Xml;
using System.Text;
public class Transportation
{
   // The SoapElementAttribute specifies that the
   // generated XML element name will be "Wheels"
   // instead of "Vehicle".
   [SoapElement("Wheels")]
   public string Vehicle;
   [SoapElement(DataType = "dateTime")]
   public DateTime CreationDate;
   [SoapElement(IsNullable = true)]
   public Thing thing;
   
}

public class Thing{ 
   [SoapElement(IsNullable=true)] public string ThingName;
}

public class Test
{
   public static void Main()
   {
      Test t = new Test();
      t.SerializeObject("SoapElementOriginal.xml");
      t.SerializeOverride("SoapElementOverride.xml");
      Console.WriteLine("Finished writing two XML files.");
   }

   // Return an XmlSerializer used for overriding.
   public XmlSerializer CreateSoapOverrider()
   {
      // Create the SoapAttributes and SoapAttributeOverrides objects.
      SoapAttributes soapAttrs = new SoapAttributes();

      SoapAttributeOverrides soapOverrides = 
      new SoapAttributeOverrides();
            
      /* Create an SoapElementAttribute to override 
      the Vehicles property. */
      SoapElementAttribute soapElement1 = 
      new SoapElementAttribute("Truck");
      // Set the SoapElement to the object.
      soapAttrs.SoapElement= soapElement1;

      /* Add the SoapAttributes to the SoapAttributeOverrides,
      specifying the member to override. */
      soapOverrides.Add(typeof(Transportation), "Vehicle", soapAttrs);
      
      // Create the XmlSerializer, and return it.
      XmlTypeMapping myTypeMapping = (new SoapReflectionImporter
      (soapOverrides)).ImportTypeMapping(typeof(Transportation));
      return new XmlSerializer(myTypeMapping);
   }

   public void SerializeOverride(string filename)
   {
      // Create an XmlSerializer instance.
      XmlSerializer ser = CreateSoapOverrider();

      // Create the object and serialize it.
      Transportation myTransportation = 
      new Transportation();

      myTransportation.Vehicle = "MyCar";
      myTransportation.CreationDate=DateTime.Now;
      myTransportation.thing = new Thing();

      XmlTextWriter writer = 
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      ser.Serialize(writer, myTransportation);
      writer.WriteEndElement();
      writer.Close();
   }
   public void SerializeObject(string filename){
      // Create an XmlSerializer instance.
      XmlSerializer ser = new XmlSerializer(typeof(Transportation));
      Transportation myTransportation = 
      new Transportation();
      myTransportation.Vehicle = "MyCar";
      myTransportation.CreationDate = DateTime.Now;
      myTransportation.thing = new Thing();
      XmlTextWriter writer = 
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      ser.Serialize(writer, myTransportation);
      writer.WriteEndElement();
      writer.Close();
   }
}
Imports System.IO
Imports System.Xml.Serialization
Imports System.Collections
Imports System.Xml
Imports System.Text

Public Class Transportation
   ' The SoapElementAttribute specifies that the
   ' generated XML element name will be "Wheels"
   ' instead of "Vehicle".
   <SoapElement("Wheels")> Public Vehicle As String 
   <SoapElement(DataType:= "dateTime")> _
   public CreationDate As DateTime    
   <SoapElement(IsNullable:= true)> _
   public thing As Thing
End Class

Public Class Thing
   <SoapElement(IsNullable:=true)> public ThingName As string 
End Class

Public Class Test

   Shared Sub Main()
      Dim t As Test = New Test()
      t.SerializeObject("SoapElementOriginalVb.xml")
      t.SerializeOverride("SoapElementOverrideVb.xml")
      Console.WriteLine("Finished writing two XML files.")
   End Sub

   ' Return an XmlSerializer used for overriding.
   Public Function CreateSoapOverrider() As XmlSerializer 
      ' Create the SoapAttributes and SoapAttributeOverrides objects.
      Dim soapAttrs As SoapAttributes = New SoapAttributes()

      Dim soapOverrides As SoapAttributeOverrides = _
      New SoapAttributeOverrides()
            
      ' Create a SoapElementAttribute to override 
      ' the Vehicles property. 
      Dim soapElement1 As SoapElementAttribute = _
      New SoapElementAttribute("Truck")
      ' Set the SoapElement to the object.
      soapAttrs.SoapElement= soapElement1

      ' Add the SoapAttributes to the SoapAttributeOverrides,
      ' specifying the member to override. 
      soapOverrides.Add(GetType(Transportation), "Vehicle", soapAttrs)
      
      ' Create the XmlSerializer, and return it.
      Dim myTypeMapping As XmlTypeMapping = (New _
      SoapReflectionImporter (soapOverrides)).ImportTypeMapping _
      (GetType(Transportation))
      return New XmlSerializer(myTypeMapping)
   End Function

   Public Sub SerializeOverride(filename As String)
      ' Create an XmlSerializer instance.
      Dim ser As XmlSerializer = CreateSoapOverrider()

      ' Create the object and serialize it.
      Dim myTransportation As Transportation = _
      New Transportation()

      myTransportation.Vehicle = "MyCar"
      myTransportation.CreationDate = DateTime.Now
      myTransportation.thing= new Thing()
      
      Dim writer As XmlTextWriter = _
      New XmlTextWriter(filename, Encoding.UTF8)
      writer.Formatting = Formatting.Indented
      writer.WriteStartElement("wrapper")
      ser.Serialize(writer, myTransportation)
      writer.WriteEndElement()
      writer.Close()
   End Sub

   Public Sub SerializeObject(filename As String)
      ' Create an XmlSerializer instance.
      Dim ser As XmlSerializer = _
      New XmlSerializer(GetType(Transportation))
      
      Dim myTransportation As Transportation = _
      New Transportation()
      
      myTransportation.Vehicle = "MyCar"
      myTransportation.CreationDate=DateTime.Now
      myTransportation.thing= new Thing()

      Dim writer As XmlTextWriter = _
      new XmlTextWriter(filename, Encoding.UTF8)
      writer.Formatting = Formatting.Indented
      writer.WriteStartElement("wrapper")
      ser.Serialize(writer, myTransportation)
      writer.WriteEndElement()
      writer.Close()
   End Sub
End Class

Комментарии

Класс принадлежит семейству атрибутов, который управляет тем XmlSerializer , как сериализует или десериализует объект как закодированный SOAP XML. SoapElementAttributeThe SoapElementAttribute class belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object as encoded SOAP XML. Результирующий XML соответствует разделу 5 документа консорциум W3C, протоколу SOAP 1,1.The resulting XML conforms to section 5 of the World Wide Web Consortium document, Simple Object Access Protocol (SOAP) 1.1. Полный список схожих атрибутов см. в разделе атрибуты, управляющие кодированной СЕРИАЛИЗАЦИЕЙ SOAP.For a complete list of similar attributes, see Attributes That Control Encoded SOAP Serialization.

Чтобы сериализовать XmlSerializer объект как закодированное сообщение SOAP, необходимо создать SoapReflectionImporter класс с XmlTypeMapping использованием класса, созданного с ImportTypeMapping помощью метода.To serialize an object as an encoded SOAP message, you must construct the XmlSerializer using an XmlTypeMapping created with the ImportTypeMapping method of the SoapReflectionImporter class.

Примените к открытому полю, чтобы указать XmlSerializer , чтобы сериализовать поле в виде закодированного XML-элемента SOAP. SoapElementAttributeApply the SoapElementAttribute to a public field to direct the XmlSerializer to serialize the field as an encoded SOAP XML element.

Дополнительные сведения об использовании атрибутов см. в разделе атрибуты.For more information about using attributes, see Attributes.

Конструкторы

SoapElementAttribute() SoapElementAttribute() SoapElementAttribute() SoapElementAttribute()

Инициализирует новый экземпляр класса SoapElementAttribute.Initializes a new instance of the SoapElementAttribute class.

SoapElementAttribute(String) SoapElementAttribute(String) SoapElementAttribute(String) SoapElementAttribute(String)

Инициализация нового экземпляра класса SoapElementAttribute и указывает имя элемента XML.Initializes a new instance of the SoapElementAttribute class and specifies the name of the XML element.

Свойства

DataType DataType DataType DataType

Получает или задает тип данных языка определения схемы XML (XSD) созданного XML-элемента.Gets or sets the XML Schema definition language (XSD) data type of the generated XML element.

ElementName ElementName ElementName ElementName

Получает или задает имя созданного XML-элементаGets or sets the name of the generated XML element.

IsNullable IsNullable IsNullable IsNullable

Получает или задает значение, указывающее, должен ли XmlSerializer выполнять сериализацию члена с заданным для атрибута xsi:null значением "1".Gets or sets a value that indicates whether the XmlSerializer must serialize a member that has the xsi:null attribute set to "1".

TypeId TypeId TypeId TypeId

При реализации в производном классе возвращает уникальный идентификатор для этого Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Методы

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

Возвращает значение, показывающее, равен ли экземпляр указанному объекту.Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Возвращает хэш-код данного экземпляра.Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Inherited from Object)

Явные реализации интерфейса

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Применяется к