XsdDataContractImporter Classe

Definição

Permite a transformação de um conjunto de arquivos de esquema XML (.xsd) em tipos CLR (Common Language Runtime).Allows the transformation of a set of XML schema files (.xsd) into common language runtime (CLR) types.

public ref class XsdDataContractImporter
public class XsdDataContractImporter
type XsdDataContractImporter = class
Public Class XsdDataContractImporter
Herança
XsdDataContractImporter

Exemplos

O exemplo a seguir cria um XmlSchemaSet e chama o Import método para criar um CodeCompileUnit .The following example creates an XmlSchemaSet and calls the Import method to create a CodeCompileUnit. O CodeCompileUnit é então usado para criar os arquivos de código do Visual C# e do Visual Basic.The CodeCompileUnit is then used to create both Visual C# and Visual Basic code files.

using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Globalization;

namespace XsdContractImporterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                XmlSchemaSet schemas = Export();
                CodeCompileUnit ccu = Import(schemas);
                CompileCode(ccu, "Person.cs");
                CompileCode(ccu, "Person.vb");
            }
            catch (Exception exc)
            {
                Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace);
            }
            finally
            {
                Console.WriteLine("Press <Enter> to end....");
                Console.ReadLine();
            }
        }

        static XmlSchemaSet Export()
        {
            XsdDataContractExporter ex = new XsdDataContractExporter();
            ex.Export(typeof(Person));
            return ex.Schemas;
        }
        static CodeCompileUnit Import(XmlSchemaSet schemas)
        {

            XsdDataContractImporter imp = new XsdDataContractImporter();

            // The EnableDataBinding option adds a RaisePropertyChanged method to
            // the generated code. The GenerateInternal causes code access to be
            // set to internal.
            ImportOptions iOptions = new ImportOptions();
            iOptions.EnableDataBinding = true;
            iOptions.GenerateInternal = true;
            imp.Options = iOptions;

            if (imp.CanImport(schemas))
            {
                imp.Import(schemas);
                return imp.CodeCompileUnit;
            }
            else
            {
                return null;
            }
        }
        static void CompileCode(CodeCompileUnit ccu, string sourceName)
        {
            CodeDomProvider provider = null;
            FileInfo sourceFile = new FileInfo(sourceName);
            // Select the code provider based on the input file extension, either C# or Visual Basic.
            if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS")
            {
                provider = new Microsoft.CSharp.CSharpCodeProvider();
            }
            else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB")
            {
                provider = new Microsoft.VisualBasic.VBCodeProvider();
            }
            else
            {
                Console.WriteLine("Source file must have a .cs or .vb extension");
            }
            if (provider != null)
            {
                CodeGeneratorOptions options = new CodeGeneratorOptions();
                // Set code formatting options to your preference.
                options.BlankLinesBetweenMembers = true;
                options.BracingStyle = "C";

                StreamWriter sw = new StreamWriter(sourceName);
                provider.GenerateCodeFromCompileUnit(ccu, sw, options);
                sw.Close();
            }
        }
    }

    [DataContract]
    public class Person
    {
        [DataMember]
        public string FirstName;

        [DataMember]
        public string LastName;

        public Person(string newFName, string newLName)
        {
            FirstName = newFName;
            LastName = newLName;
        }
    }
}
Imports System.CodeDom.Compiler
Imports System.CodeDom
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Xml
Imports System.Xml.Schema
Imports System.Globalization

Class Program
   
    Shared Sub Main(ByVal args() As String) 
        Try
            Dim schemas As XmlSchemaSet = Export()
            Dim ccu As CodeCompileUnit = Import(schemas)
            CompileCode(ccu, "Person.cs")
            CompileCode(ccu, "Person.vb")
        Catch exc As Exception
            Console.WriteLine("{0}: {1}", exc.Message, exc.StackTrace)
        Finally
            Console.WriteLine("Press <Enter> to end....")
            Console.ReadLine()
        End Try
    
    End Sub 
    
    Shared Function Export() As XmlSchemaSet 
        Dim ex As New XsdDataContractExporter()
        ex.Export(GetType(Person))
        Return ex.Schemas
    End Function
    Shared Function Import(ByVal schemas As XmlSchemaSet) As CodeCompileUnit 

        Dim imp As New XsdDataContractImporter()
       ' The EnableDataBinding option adds a RaisePropertyChanged method to
       ' the generated code. The GenerateInternal causes code access to be
       ' set to internal.
       Dim iOptions As New ImportOptions()
       iOptions.EnableDataBinding = true
       iOptions.GenerateInternal = true
       imp.Options = IOptions

        If imp.CanImport(schemas) Then
            imp.Import(schemas)
            Return imp.CodeCompileUnit
        Else
            Return Nothing
        End If
    End Function

    Shared Sub CompileCode(ByVal ccu As CodeCompileUnit, ByVal sourceName As String) 
        Dim provider As CodeDomProvider = Nothing
        Dim sourceFile As New FileInfo(sourceName)
        ' Select the code provider based on the input file extension, either C# or Visual Basic.
        If sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".CS" Then
            provider = New Microsoft.CSharp.CSharpCodeProvider()
        ElseIf sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".VB" Then
            provider = New Microsoft.VisualBasic.VBCodeProvider()
        Else
            Console.WriteLine("Source file must have a .cs or .vb extension")
        End If
        If Not (provider Is Nothing) Then
            Dim options As New CodeGeneratorOptions()
            ' Set code formatting options to your preference. 
            options.BlankLinesBetweenMembers = True
            options.BracingStyle = "C"
            
            Dim sw As New StreamWriter(sourceName)
            provider.GenerateCodeFromCompileUnit(ccu, sw, options)
            sw.Close()
        End If
    
    End Sub
End Class

<DataContract()>  _
Public Class Person
    <DataMember()>  _
    Public FirstName As String
    
    <DataMember()>  _
    Public LastName As String
    
    
    Public Sub New(ByVal newFName As String, ByVal newLName As String) 
        FirstName = newFName
        LastName = newLName
    
    End Sub 
End Class 

Comentários

Use o XsdDataContractImporter se você estiver criando um serviço Web que deve interoperar com um serviço Web existente ou para criar tipos de contrato de dados de esquemas XML.Use the XsdDataContractImporter if you are creating a Web service that must interoperate with an existing Web service, or to create data contract types from XML schemas. XsdDataContractImporter o irá transformar um conjunto de esquemas XML e criará os tipos de .NET Framework que representam o contrato de dados em uma linguagem de programação selecionada.XsdDataContractImporter will transform a set of XML schemas and create the .NET Framework types that represent the data contract in a selected programming language. Para criar o código, use as classes no System.CodeDom namespace.To create the code, use the classes in the System.CodeDom namespace.

Por outro lado, use a XsdDataContractExporter classe quando você tiver criado um serviço Web que incorpora dados representados por tipos CLR e quando você precisa exportar esquemas XML para cada tipo de dados a ser consumido por outros serviços Web.Conversely, use the XsdDataContractExporter class when you have created a Web service that incorporates data represented by CLR types and when you need to export XML schemas for each data type to be consumed by other Web services. Ou seja, XsdDataContractExporter transforma um conjunto de tipos CLR em um conjunto de esquemas XML.That is, XsdDataContractExporter transforms a set of CLR types into a set of XML schemas.

Observação

Para gerar tipos CLR de esquemas XML em tempo de design, use a ferramenta de utilitário de metadados ServiceModel (Svcutil.exe).To generate CLR types from XML schemas at design time, use the ServiceModel Metadata Utility Tool (Svcutil.exe). Para gerar o código de arquivos XSD, use a /dataContractOnly opção da ferramenta.To generated code from XSD files, use the /dataContractOnly switch of the tool. Você também pode usar o XsdDataContractImporter se precisar de mais controle sobre o processo ou precisar fazê-lo programaticamente.You can also use the XsdDataContractImporter if you need more control over the process or need to do it programmatically.

Construtores

XsdDataContractImporter()

Inicializa uma nova instância da classe XsdDataContractImporter.Initializes a new instance of the XsdDataContractImporter class.

XsdDataContractImporter(CodeCompileUnit)

Inicializa uma nova instância da classe XsdDataContractImporter com o CodeCompileUnit que será usado para gerar o código CLR.Initializes a new instance of the XsdDataContractImporter class with the CodeCompileUnit that will be used to generate CLR code.

Propriedades

CodeCompileUnit

Obtém um CodeCompileUnit usado para armazenar os tipos CLR gerados.Gets a CodeCompileUnit used for storing the CLR types generated.

Options

Obtém ou define um ImportOptions que contém opções configuráveis para a operação de importação.Gets or sets an ImportOptions that contains settable options for the import operation.

Métodos

CanImport(XmlSchemaSet)

Obtém um valor que indica se os esquemas contidos em um XmlSchemaSet podem ser transformados em um CodeCompileUnit.Gets a value that indicates whether the schemas contained in an XmlSchemaSet can be transformed into a CodeCompileUnit.

CanImport(XmlSchemaSet, ICollection<XmlQualifiedName>)

Obtém um valor que indica se o conjunto especificado de tipos contidos em um XmlSchemaSet pode ser transformado em tipos CLR gerados em um CodeCompileUnit.Gets a value that indicates whether the specified set of types contained in an XmlSchemaSet can be transformed into CLR types generated into a CodeCompileUnit.

CanImport(XmlSchemaSet, XmlQualifiedName)

Obtém um valor que indica se os esquemas contidos em um XmlSchemaSet podem ser transformados em um CodeCompileUnit.Gets a value that indicates whether the schemas contained in an XmlSchemaSet can be transformed into a CodeCompileUnit.

CanImport(XmlSchemaSet, XmlSchemaElement)

Obtém um valor que indica se um elemento de esquema específico contido em um XmlSchemaSet pode ser importado.Gets a value that indicates whether a specific schema element contained in an XmlSchemaSet can be imported.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetCodeTypeReference(XmlQualifiedName)

Retorna um CodeTypeReference para o tipo CLR gerado para o tipo de esquema com o XmlQualifiedName especificado.Returns a CodeTypeReference to the CLR type generated for the schema type with the specified XmlQualifiedName.

GetCodeTypeReference(XmlQualifiedName, XmlSchemaElement)

Retorna um CodeTypeReference para o elemento XML qualificado e o elemento de esquema.Returns a CodeTypeReference for the specified XML qualified element and schema element.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetKnownTypeReferences(XmlQualifiedName)

Retorna uma lista de objetos CodeTypeReference que representam os tipos conhecidos gerados durante a geração de código para o tipo de esquema especificado.Returns a list of CodeTypeReference objects that represents the known types generated when generating code for the specified schema type.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
Import(XmlSchemaSet)

Transforma o conjunto especificado de esquemas XML contidos em um XmlSchemaSet em um CodeCompileUnit.Transforms the specified set of XML schemas contained in an XmlSchemaSet into a CodeCompileUnit.

Import(XmlSchemaSet, ICollection<XmlQualifiedName>)

Transforma o conjunto especificado de tipos de esquema contido em um XmlSchemaSet em tipos CLR gerados em um CodeCompileUnit.Transforms the specified set of schema types contained in an XmlSchemaSet into CLR types generated into a CodeCompileUnit.

Import(XmlSchemaSet, XmlQualifiedName)

Transforma o tipo de esquema XML especificado contido em um XmlSchemaSet em um CodeCompileUnit.Transforms the specified XML schema type contained in an XmlSchemaSet into a CodeCompileUnit.

Import(XmlSchemaSet, XmlSchemaElement)

Transforma o elemento de esquema especificado no conjunto de esquemas XML fornecido em um CodeCompileUnit e retorna um XmlQualifiedName que representa o nome de contrato de dados para o elemento indicado.Transforms the specified schema element in the set of specified XML schemas into a CodeCompileUnit and returns an XmlQualifiedName that represents the data contract name for the specified element.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Aplica-se a

Confira também