Share via


XmlElementAttribute.DataType Propriedade

Definição

Obtém ou define o tipo de dados XSD (definição de esquema XML) do elemento XML gerado pelo XmlSerializer.

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

Valor da propriedade

String

Um tipo de dados de esquema XML.

Exceções

O tipo de dados de esquema XML que você especificou não pode ser mapeado para o tipo de dados .NET.

Exemplos

O exemplo a seguir serializa uma classe nomeada Group que contém um campo chamado ExtraInfo, que retorna um ArrayList. O exemplo aplica duas instâncias do XmlElementAttribute campo e especifica valores diferentes DataType para cada instância. Cada instância permite serializar os tipos especificados inseridos XmlSerializer na matriz.

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

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

   /* Apply two XmlElementAttributes to the field. Set the DataType
      to string an int to allow the ArrayList to accept 
      both types. The Namespace is also set to different values
      for each type. */

   [XmlElement(DataType="string",
   Type=String::typeid,
   Namespace="http://www.cpandl.com"),
   XmlElement(DataType="snippet1>",
   Namespace="http://www.cohowinery.com",
   Type=Int32::typeid)]
   ArrayList^ ExtraInfo;
};

void SerializeObject( String^ filename )
{
   // A TextWriter is needed to write the file.
   TextWriter^ writer = gcnew StreamWriter( filename );

   // Create the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Group::typeid );

   // Create the object to serialize.
   Group^ myGroup = gcnew Group;

   /* Add a string and an integer to the ArrayList returned
      by the ExtraInfo field. */
   myGroup->ExtraInfo = gcnew ArrayList;
   myGroup->ExtraInfo->Add( "hello" );
   myGroup->ExtraInfo->Add( 100 );

   // Serialize the object and close the TextWriter.
   s->Serialize( writer, myGroup );
   writer->Close();
}

int main()
{
   SerializeObject( "ElementTypes.xml" );
}
using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

public class Group
{
   /* Apply two XmlElementAttributes to the field. Set the DataType
      to string an int to allow the ArrayList to accept
      both types. The Namespace is also set to different values
      for each type. */
   [XmlElement(DataType = "string",
   Type = typeof(string),
   Namespace = "http://www.cpandl.com"),
   XmlElement(DataType = "int",
   Namespace = "http://www.cohowinery.com",
   Type = typeof(int))]
   public ArrayList ExtraInfo;
}

public class Run
{
    public static void Main()
    {
       Run test = new Run();
       test.SerializeObject("ElementTypes.xml");
          }

    public void SerializeObject(string filename)
    {
      // A TextWriter is needed to write the file.
      TextWriter writer = new StreamWriter(filename);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Group));

      // Create the object to serialize.
      Group myGroup = new Group();

      /* Add a string and an integer to the ArrayList returned
         by the ExtraInfo field. */
      myGroup.ExtraInfo = new ArrayList();
      myGroup.ExtraInfo.Add("hello");
      myGroup.ExtraInfo.Add(100);

      // Serialize the object and close the TextWriter.
      s.Serialize(writer,myGroup);
      writer.Close();
   }
}
Imports System.Collections
Imports System.IO
Imports System.Xml.Serialization


Public Class Group
    ' Apply two XmlElementAttributes to the field. Set the DataType
    ' to string and int to allow the ArrayList to accept
    ' both types. The Namespace is also set to different values
    ' for each type. 
    <XmlElement(DataType := "string", _
        Type := GetType(String), _
        Namespace := "http://www.cpandl.com"), _
     XmlElement(DataType := "int", _                    
        Type := GetType(Integer), _
        Namespace := "http://www.cohowinery.com")> _
    Public ExtraInfo As ArrayList
End Class


Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("ElementTypes.xml")
    End Sub    
    
    Public Sub SerializeObject(filename As String)
        ' A TextWriter is needed to write the file.
        Dim writer As New StreamWriter(filename)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Group))
        
        ' Create the object to serialize.
        Dim myGroup As New Group()
        
        ' Add a string and an integer to the ArrayList returned
        ' by the ExtraInfo field. 
        myGroup.ExtraInfo = New ArrayList()
        myGroup.ExtraInfo.Add("hello")
        myGroup.ExtraInfo.Add(100)
        
        ' Serialize the object and close the TextWriter.
        s.Serialize(writer, myGroup)
        writer.Close()
    End Sub
End Class

Comentários

A tabela a seguir lista os tipos de dados simples do Esquema XML com equivalentes their.NET.

Para os tipos de base64Binary dados e hexBinary esquema XML, use uma matriz de Byte estruturas e aplique um XmlElementAttribute com o DataType conjunto para "base64Binary" ou "hexBinary", conforme apropriado. Para os tipos de time dados e date esquema XML, use o DateTime tipo e aplique o XmlElementAttribute com o DataType conjunto como "data" ou "hora".

Para cada tipo de esquema XML mapeado para uma cadeia de caracteres, aplique-o XmlElementAttribute com sua DataType propriedade definida para o tipo de esquema XML. É possível que isso possa alterar o formato de serialização, não apenas o esquema do membro.

Observação

A propriedade diferencia maiúsculas de minúsculas, portanto, você deve defini-la exatamente como um dos tipos de dados de esquema XML.

Observação

Passar dados binários como um elemento XML é mais eficiente do que passá-los como um atributo de Esquema XML.

Para obter mais informações sobre tipos de dados XML, consulte o documento do World Wide Web Consortium chamado Esquema XML Parte 2: Tipos de dados.

Tipo de dados XSD Tipo de dados .NET
anyURI String
Base64binary Matriz de objetos Byte
booleano Boolean
byte SByte
Data DateTime
dateTime DateTime
decimal Decimal
double Double
ENTITY String
ENTIDADES String
FLOAT Single
gDay String
gMonth String
gMonthDay String
gYear String
gYearMonth String
Hexbinary Matriz de objetos Byte
ID String
IDREF String
IDREFS String
INT Int32
Número inteiro String
Linguagem String
long Int64
Nome String
{1>NCName<1} String
negativeInteger String
NMTOKEN String
NMTOKENS String
normalizedString String
nonNegativeInteger String
nonPositiveInteger String
NOTATION String
positiveInteger String
QName XmlQualifiedName
duration String
string String
short Int16
time DateTime
token String
unsignedByte Byte
unsignedInt UInt32
unsignedLong UInt64
unsignedShort UInt16

Aplica-se a