SoapElementAttribute.DataType SoapElementAttribute.DataType SoapElementAttribute.DataType SoapElementAttribute.DataType Property

Определение

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

public:
 property System::String ^ DataType { System::String ^ get(); void set(System::String ^ value); };
public string DataType { get; set; }
member this.DataType : string with get, set
Public Property DataType As String

Значение свойства

Один из типов данных XML-схемы.One of the XML Schema data types.

Примеры

В следующем примере сериализуется экземпляр класса с именем 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

Комментарии

В следующей таблице перечислены простые типы данных схемы XML с их эквивалентами .NET.The following table lists the XML Schema simple data types with their .NET equivalents.

Для XML-схемы base64Binary и hexBinary типов данных используйте массив Byte структур и применяйте объект SoapElementAttribute со DataType значением «base64Binary» или «hexBinary», соответствующим образом.For the XML Schema base64Binary and hexBinary data types, use an array of Byte structures, and apply a SoapElementAttribute with the DataType set to "base64Binary" or "hexBinary", as appropriate. time Для схемы DataType XML и date типов DateTime данных используйте тип и примените SoapElementAttribute атрибут со значением "Date" или "Time".For the XML Schema time and date data types, use the DateTime type and apply the SoapElementAttribute with the DataType set to "date" or "time".

Для каждого типа данных схемы XML, сопоставленного со строкой, примените SoapElementAttribute DataType свойство со свойством, установленным в тип схемы XML.For every XML Schema data type that is mapped to a string, apply the SoapElementAttribute with its DataType property set to the XML Schema type. Обратите внимание, что это не изменяет формат сериализации, а только схему для элемента.Note that this does not change the serialization format, only the schema for the member.

Примечание

В свойстве учитывается регистр, поэтому его необходимо задать в точности до одного из типов данных схемы XML.The property is case-sensitive, so you must set it exactly to one of the XML Schema data types.

Примечание

Передача двоичных данных в виде XML-элемента более эффективна, чем передача их в виде XML-атрибута.Passing binary data as an XML element is more efficient than passing it as an XML attribute.

Дополнительные сведения о типах данных XML см. в документе консорциум W3C, схема XML, часть 2. Типы типов.For more information about XML data types, see the World Wide Web Consortium document, XML Schema Part 2: Datatypes.

Тип данных XSDXSD data type Тип данных .NET.NET data type
anyURIanyURI String
base64Binarybase64Binary Byte Массив объектовArray of Byte objects
booleanboolean Boolean
bytebyte SByte
datedate DateTime
dateTimedateTime DateTime
decimaldecimal Decimal
doubledouble Double
ENTITYENTITY String
ОБЪЕКТАХENTITIES String
floatfloat Single
гдайgDay String
гмонсgMonth String
гмонсдайgMonthDay String
геарgYear String
gYearMonthgYearMonth String
hexBinaryhexBinary Byte Массив объектовArray of Byte objects
IDID String
IDREFIDREF String
IDREFSIDREFS String
intint Int32
целочисленныйinteger String
языкlanguage String
longlong Int64
nameName String
NCNameNCName String
негативеинтежерnegativeInteger String
NMTOKENNMTOKEN String
NMTOKENSNMTOKENS String
normalizedStringnormalizedString String
nonNegativeIntegernonNegativeInteger String
нонпоситивеинтежерnonPositiveInteger String
NOTATIONNOTATION String
поситивеинтежерpositiveInteger String
QNameQName XmlQualifiedName
длительностьduration String
stringstring String
shortshort Int16
времяtime DateTime
tokentoken String
unsignedByteunsignedByte Byte
unsignedIntunsignedInt UInt32
unsignedLongunsignedLong UInt64
unsignedShortunsignedShort UInt16

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