XmlElementAttribute.DataType Propriedade

Definição

Obtém ou define o tipo de dados XML Schema definition (XSD) 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 de Propriedade

Um tipo de dado XML Schema.

Exceções

O tipo de dado XML Schema que especificou não pode ser mapeado para o tipo de dado .NET.

Exemplos

O exemplo seguinte serializa uma classe nomeada Group que contém um corpo chamado ExtraInfo, que retorna um ArrayList. O exemplo aplica duas instâncias de ao XmlElementAttribute campo e especifica valores diferentes DataType para cada instância. Cada instância permite serializar XmlSerializer os tipos especificados inseridos no array.

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

Observações

A tabela seguinte lista os tipos de dados simples do XML Schema com os seus equivalentes .NET.

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

Para cada tipo de Esquema XML que seja mapeado para uma cadeia, aplique o XmlElementAttribute com a sua DataType propriedade definida para o tipo de Esquema XML. É possível que isto altere o formato de serialização, não apenas o esquema do membro.

Note

A propriedade é sensível a maiúsculas e minúsculas, por isso deve defini-la exatamente para um dos tipos de dados XML Schema.

Note

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

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

Tipo de dados XSD Tipo de dados .NET
anyURI String
base64Binary Array de Byte objetos
boolean Boolean
byte SByte
date DateTime
data e hora DateTime
decimal Decimal
duplo Double
ENTIDADE String
ENTIDADES String
float Single
gDay String
gMonth String
gMonthDay String
gYear String
gAnoMes String
hexBinary Array de Byte objetos
ID String
IDREF String
IDREFS String
int Int32
número inteiro String
linguagem String
long Int64
Name String
NCName String
negativoInteger String
NMTOKEN String
NMTOKENS String
normalizedString String
nãoNegativoInteiro String
nãoPositivoInteger String
NOÇÃO String
Inteiro positivo String
QName XmlQualifiedName
duration String
cadeia (de caracteres) String
curto Int16
time DateTime
token String
byte não assinado Byte
inteiroSemSinal UInt32
não assinadoLong UInt64
unsignedShort UInt16

Aplica-se a