XmlSchema XmlSchema XmlSchema XmlSchema Class

Definição

Uma representação na memória de um esquema XML, conforme especificado em XML Schema Part 1: Structures (Esquema XML Parte 1: Estruturas) e XML Schema Part 2: Datatypes] (Esquema XML Parte 2: Tipos de dados) do W3C (World Wide Web Consortium).An in-memory representation of an XML Schema, as specified in the World Wide Web Consortium (W3C) XML Schema Part 1: Structures and XML Schema Part 2: Datatypes].

public ref class XmlSchema : System::Xml::Schema::XmlSchemaObject
public class XmlSchema : System.Xml.Schema.XmlSchemaObject
type XmlSchema = class
    inherit XmlSchemaObject
Public Class XmlSchema
Inherits XmlSchemaObject
Herança

Exemplos

O exemplo a seguir cria uma definição de esquema.The following example creates a schema definition.

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

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Schema;

class XmlSchemaExamples
{
public:
	static void Main()
	{

		XmlSchema^ schema = gcnew XmlSchema();

		// <xs:element name="cat" type="xs:string"/>
		XmlSchemaElement^ elementCat = gcnew XmlSchemaElement();
		schema->Items->Add(elementCat);
		elementCat->Name = "cat";
		elementCat->SchemaTypeName = gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

		// <xs:element name="dog" type="xs:string"/>
		XmlSchemaElement^ elementDog = gcnew XmlSchemaElement();
		schema->Items->Add(elementDog);
		elementDog->Name = "dog";
		elementDog->SchemaTypeName = gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

		// <xs:element name="redDog" substitutionGroup="dog" />
		XmlSchemaElement^ elementRedDog = gcnew XmlSchemaElement();
		schema->Items->Add(elementRedDog);
		elementRedDog->Name = "redDog";
		elementRedDog->SubstitutionGroup = gcnew XmlQualifiedName("dog");

		// <xs:element name="brownDog" substitutionGroup ="dog" />
		XmlSchemaElement^ elementBrownDog = gcnew XmlSchemaElement();
		schema->Items->Add(elementBrownDog);
		elementBrownDog->Name = "brownDog";
		elementBrownDog->SubstitutionGroup = gcnew XmlQualifiedName("dog");


		// <xs:element name="pets">
		XmlSchemaElement^ elementPets = gcnew XmlSchemaElement();
		schema->Items->Add(elementPets);
		elementPets->Name = "pets";

		// <xs:complexType>
		XmlSchemaComplexType^ complexType = gcnew XmlSchemaComplexType();
		elementPets->SchemaType = complexType;

		// <xs:choice minOccurs="0" maxOccurs="unbounded">
		XmlSchemaChoice^ choice = gcnew XmlSchemaChoice();
		complexType->Particle = choice;
		choice->MinOccurs = 0;
		choice->MaxOccursString = "unbounded";

		// <xs:element ref="cat"/>
		XmlSchemaElement^ catRef = gcnew XmlSchemaElement();
		choice->Items->Add(catRef);
		catRef->RefName = gcnew XmlQualifiedName("cat");

		// <xs:element ref="dog"/>
		XmlSchemaElement^ dogRef = gcnew XmlSchemaElement();
		choice->Items->Add(dogRef);
		dogRef->RefName = gcnew XmlQualifiedName("dog");

		XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet();
		schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallbackOne);
		schemaSet->Add(schema);
		schemaSet->Compile();

		XmlSchema^ compiledSchema;

		for each (XmlSchema^ schema1 in schemaSet->Schemas())
		{
			compiledSchema = schema1;
		}

		XmlNamespaceManager^ nsmgr = gcnew XmlNamespaceManager(gcnew NameTable());
		nsmgr->AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
		compiledSchema->Write(Console::Out, nsmgr);
	}

	static void ValidationCallbackOne(Object^ sender, ValidationEventArgs^ args)
	{
		Console::WriteLine(args->Message);
	}
};

int main()
{
	XmlSchemaExamples::Main();
	return 0;
};
using System;
using System.Xml;
using System.Xml.Schema;

class XMLSchemaExamples
{
    public static void Main()
    {

        XmlSchema schema = new XmlSchema();

        // <xs:element name="cat" type="xs:string"/>
        XmlSchemaElement elementCat = new XmlSchemaElement();
        schema.Items.Add(elementCat);
        elementCat.Name = "cat";
        elementCat.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // <xs:element name="dog" type="xs:string"/>
        XmlSchemaElement elementDog = new XmlSchemaElement();
        schema.Items.Add(elementDog);
        elementDog.Name = "dog";
        elementDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // <xs:element name="redDog" substitutionGroup="dog" />
        XmlSchemaElement elementRedDog = new XmlSchemaElement();
        schema.Items.Add(elementRedDog);
        elementRedDog.Name = "redDog";
        elementRedDog.SubstitutionGroup = new XmlQualifiedName("dog");

        // <xs:element name="brownDog" substitutionGroup ="dog" />
        XmlSchemaElement elementBrownDog = new XmlSchemaElement();
        schema.Items.Add(elementBrownDog);
        elementBrownDog.Name = "brownDog";
        elementBrownDog.SubstitutionGroup = new XmlQualifiedName("dog");


        // <xs:element name="pets">
        XmlSchemaElement elementPets = new XmlSchemaElement();
        schema.Items.Add(elementPets);
        elementPets.Name = "pets";

        // <xs:complexType>
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();
        elementPets.SchemaType = complexType;

        // <xs:choice minOccurs="0" maxOccurs="unbounded">
        XmlSchemaChoice choice = new XmlSchemaChoice();
        complexType.Particle = choice;
        choice.MinOccurs = 0;
        choice.MaxOccursString = "unbounded";

        // <xs:element ref="cat"/>
        XmlSchemaElement catRef = new XmlSchemaElement();
        choice.Items.Add(catRef);
        catRef.RefName = new XmlQualifiedName("cat");

        // <xs:element ref="dog"/>
        XmlSchemaElement dogRef = new XmlSchemaElement();
        choice.Items.Add(dogRef);
        dogRef.RefName = new XmlQualifiedName("dog");

        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }

    public static void ValidationCallbackOne(object sender, ValidationEventArgs args)
    {
        Console.WriteLine(args.Message);
    }
}
Option Explicit On
Option Strict On

Imports System
Imports System.Xml
Imports System.Xml.Schema

Class XMLSchemaExamples
    Public Shared Sub Main()
        Dim schema As New XmlSchema()

        ' <xs:element name="cat" type="xs:string"/>
        Dim elementCat As New XmlSchemaElement()
        schema.Items.Add(elementCat)
        elementCat.Name = "cat"
        elementCat.SchemaTypeName = New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")

        ' <xs:element name="dog" type="xs:string"/>
        Dim elementDog As New XmlSchemaElement()
        schema.Items.Add(elementDog)
        elementDog.Name = "dog"
        elementDog.SchemaTypeName = New XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")

        ' <xs:element name="redDog" substitutionGroup="dog" />
        Dim elementRedDog As New XmlSchemaElement()
        schema.Items.Add(elementRedDog)
        elementRedDog.Name = "redDog"
        elementRedDog.SubstitutionGroup = New XmlQualifiedName("dog")

        ' <xs:element name="brownDog" substitutionGroup ="dog" />
        Dim elementBrownDog As New XmlSchemaElement()
        schema.Items.Add(elementBrownDog)
        elementBrownDog.Name = "brownDog"
        elementBrownDog.SubstitutionGroup = New XmlQualifiedName("dog")

        ' <xs:element name="pets">
        Dim elementPets As New XmlSchemaElement()
        schema.Items.Add(elementPets)
        elementPets.Name = "pets"

        ' <xs:complexType>
        Dim complexType As New XmlSchemaComplexType()
        elementPets.SchemaType = complexType

        ' <xs:choice minOccurs="0" maxOccurs="unbounded">
        Dim choice As New XmlSchemaChoice()
        complexType.Particle = choice
        choice.MinOccurs = 0
        choice.MaxOccursString = "unbounded"

        ' <xs:element ref="cat"/>
        Dim catRef As New XmlSchemaElement()
        choice.Items.Add(catRef)
        catRef.RefName = New XmlQualifiedName("cat")

        ' <xs:element ref="dog"/>
        Dim dogRef As New XmlSchemaElement()
        choice.Items.Add(dogRef)
        dogRef.RefName = New XmlQualifiedName("dog")

        Dim schemaSet As New XmlSchemaSet()
        AddHandler schemaSet.ValidationEventHandler, AddressOf ValidationCallbackOne

        schemaSet.Add(schema)
        schemaSet.Compile()

        Dim compiledSchema As XmlSchema = Nothing

        For Each schema1 As XmlSchema In schemaSet.Schemas()
            compiledSchema = schema1
        Next

        Dim nsmgr As New XmlNamespaceManager(New NameTable())
        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema")
        compiledSchema.Write(Console.Out, nsmgr)


    End Sub 'Main


    Public Shared Sub ValidationCallbackOne(ByVal sender As Object, ByVal args As ValidationEventArgs)
        Console.WriteLine(args.Message)
    End Sub 'ValidationCallbackOne
End Class 'XMLSchemaExamples

O seguinte arquivo XML é gerado para o exemplo de código anterior.The following XML file is generated for the preceding code example.


<?xml version="1.0" encoding="IBM437"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="cat" type="xs:string"/>
    <xs:element name="dog" type="xs:string"/>
    <xs:element name="redDog" type="xs:string" substitutionGroup="dog"/>
    <xs:element name="brownDog" type="xs:string" substitutionGroup ="dog" />

    <xs:element name="pets">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element ref="cat"/>
          <xs:element ref="dog"/>
        </xs:choice>
      </xs:complexType>
    </xs:element>
</xs:schema>

Comentários

Importante

  • Não use esquemas de fontes desconhecidas ou não confiáveis ou locais.Do not use schemas from unknown or untrusted sources or locations. Ao fazer isso comprometerá a segurança do seu código.Doing so will compromise the security of your code.
  • Esquemas XML (incluindo esquemas in-line) são inerentemente vulneráveis a ataques negação de serviço; não aceitá-los em cenários não confiáveis.XML schemas (including inline schemas) are inherently vulnerable to denial of service attacks; do not accept them in untrusted scenarios.
  • As exceções geradas como resultado do uso de XmlSchema classe, como o XmlSchemaException de classe, podem conter informações confidenciais não devem ser expostas em cenários não confiáveis.Exceptions raised as a result of using the XmlSchema class, such as the XmlSchemaException class, may contain sensitive information that should not be exposed in untrusted scenarios. Por exemplo, o SourceUri propriedade de um XmlSchemaException retorna o caminho URI para o arquivo de esquema que causou a exceção.For example, the SourceUri property of an XmlSchemaException returns the URI path to the schema file that caused the exception. O SourceUri propriedade não deve ser exposta em cenários não confiáveis.The SourceUri property should not be exposed in untrusted scenarios. As exceções devem ser manipuladas corretamente para que essas informações confidenciais não são expostas em cenários não confiáveis.Exceptions should be properly handled so this sensitive information is not exposed in untrusted scenarios.

Construtores

XmlSchema() XmlSchema() XmlSchema() XmlSchema()

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

Campos

InstanceNamespace InstanceNamespace InstanceNamespace InstanceNamespace

O namespace da instância do esquema XML.The XML schema instance namespace. Este campo é constante.This field is constant.

Namespace Namespace Namespace Namespace

O namespace do esquema XML.The XML schema namespace. Este campo é constante.This field is constant.

Propriedades

AttributeFormDefault AttributeFormDefault AttributeFormDefault AttributeFormDefault

Obtém ou define o formulário dos atributos declarados no namespace de destino do esquema.Gets or sets the form for attributes declared in the target namespace of the schema.

AttributeGroups AttributeGroups AttributeGroups AttributeGroups

Obtém o valor de pós-compilação de esquema de todos os grupos de atributos globais no esquema.Gets the post-schema-compilation value of all the global attribute groups in the schema.

Attributes Attributes Attributes Attributes

Obtém o valor de pós-compilação de esquema de todos os atributos no esquema.Gets the post-schema-compilation value for all the attributes in the schema.

BlockDefault BlockDefault BlockDefault BlockDefault

Obtém ou define o atributo blockDefault que define o valor padrão do atributo block no elemento e tipos complexos no targetNamespace do esquema.Gets or sets the blockDefault attribute which sets the default value of the block attribute on element and complex types in the targetNamespace of the schema.

ElementFormDefault ElementFormDefault ElementFormDefault ElementFormDefault

Obtém ou define o formulário dos elementos declarados no namespace de destino do esquema.Gets or sets the form for elements declared in the target namespace of the schema.

Elements Elements Elements Elements

Obtém o valor de compilação pós-esquema para todos os elementos no esquema.Gets the post-schema-compilation value for all the elements in the schema.

FinalDefault FinalDefault FinalDefault FinalDefault

Obtém ou define o atributo finalDefault que define o valor padrão do atributo final nos elementos e tipos complexos no namespace de destino do esquema.Gets or sets the finalDefault attribute which sets the default value of the final attribute on elements and complex types in the target namespace of the schema.

Groups Groups Groups Groups

Obtém o valor de pós-compilação de esquema de todos os grupos no esquema.Gets the post-schema-compilation value of all the groups in the schema.

Id Id Id Id

Obtém ou define a ID de cadeia de caracteres.Gets or sets the string ID.

Includes Includes Includes Includes

Obtém a coleção de esquemas incluídos e importados.Gets the collection of included and imported schemas.

IsCompiled IsCompiled IsCompiled IsCompiled

Indica se o esquema foi compilado.Indicates if the schema has been compiled.

Items Items Items Items

Obtém a coleção de elementos de esquema no esquema e é usado para adicionar novos tipos de elemento no nível de elemento schema.Gets the collection of schema elements in the schema and is used to add new element types at the schema element level.

LineNumber LineNumber LineNumber LineNumber

Obtém ou define o número de linha no arquivo ao qual o elemento schema se refere.Gets or sets the line number in the file to which the schema element refers.

(Inherited from XmlSchemaObject)
LinePosition LinePosition LinePosition LinePosition

Obtém ou define a posição da linha no arquivo ao qual o elemento schema se refere.Gets or sets the line position in the file to which the schema element refers.

(Inherited from XmlSchemaObject)
Namespaces Namespaces Namespaces Namespaces

Obtém ou define o XmlSerializerNamespaces a ser usado com esse objeto de esquema.Gets or sets the XmlSerializerNamespaces to use with this schema object.

(Inherited from XmlSchemaObject)
Notations Notations Notations Notations

Obtém o valor de pós-compilação de esquema para todas as notações no esquema.Gets the post-schema-compilation value for all notations in the schema.

Parent Parent Parent Parent

Obtém ou define o pai deste XmlSchemaObject.Gets or sets the parent of this XmlSchemaObject.

(Inherited from XmlSchemaObject)
SchemaTypes SchemaTypes SchemaTypes SchemaTypes

Obtém o valor de pós-compilação de esquema de todos os tipos de esquema no esquema.Gets the post-schema-compilation value of all schema types in the schema.

SourceUri SourceUri SourceUri SourceUri

Obtém ou define o local de origem para o arquivo que carregou o esquema.Gets or sets the source location for the file that loaded the schema.

(Inherited from XmlSchemaObject)
TargetNamespace TargetNamespace TargetNamespace TargetNamespace

Obtém ou define o URI (Uniform Resource Identifier) do namespace de destino do esquema.Gets or sets the Uniform Resource Identifier (URI) of the schema target namespace.

UnhandledAttributes UnhandledAttributes UnhandledAttributes UnhandledAttributes

Obtém ou define os atributos qualificados que não pertencem ao namespace de destino do esquema.Gets or sets the qualified attributes which do not belong to the schema target namespace.

Version Version Version Version

Obtém ou define a versão do esquema.Gets or sets the version of the schema.

Métodos

Compile(ValidationEventHandler) Compile(ValidationEventHandler) Compile(ValidationEventHandler) Compile(ValidationEventHandler)

Compila o SOM (Modelo de Objeto de Esquema XML) em informações de esquema para validação.Compiles the XML Schema Object Model (SOM) into schema information for validation. Usado para verificar a estrutura sintática e semântica do SOM criado de forma programática.Used to check the syntactic and semantic structure of the programmatically built SOM. A verificação de validação semântica é executada durante a compilação.Semantic validation checking is performed during compilation.

Compile(ValidationEventHandler, XmlResolver) Compile(ValidationEventHandler, XmlResolver) Compile(ValidationEventHandler, XmlResolver) Compile(ValidationEventHandler, XmlResolver)

Compila o SOM (Modelo de Objeto de Esquema XML) em informações de esquema para validação.Compiles the XML Schema Object Model (SOM) into schema information for validation. Usado para verificar a estrutura sintática e semântica do SOM criado de forma programática.Used to check the syntactic and semantic structure of the programmatically built SOM. A verificação de validação semântica é executada durante a compilação.Semantic validation checking is performed during compilation.

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

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

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
Read(Stream, ValidationEventHandler) Read(Stream, ValidationEventHandler) Read(Stream, ValidationEventHandler) Read(Stream, ValidationEventHandler)

Lê um Esquema XML do fluxo fornecido.Reads an XML Schema from the supplied stream.

Read(TextReader, ValidationEventHandler) Read(TextReader, ValidationEventHandler) Read(TextReader, ValidationEventHandler) Read(TextReader, ValidationEventHandler)

Lê um Esquema XML do TextReader fornecido.Reads an XML Schema from the supplied TextReader.

Read(XmlReader, ValidationEventHandler) Read(XmlReader, ValidationEventHandler) Read(XmlReader, ValidationEventHandler) Read(XmlReader, ValidationEventHandler)

Lê um Esquema XML do XmlReader fornecido.Reads an XML Schema from the supplied XmlReader.

ToString() ToString() ToString() ToString()

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

(Inherited from Object)
Write(Stream) Write(Stream) Write(Stream) Write(Stream)

Grava o esquema XML no fluxo de dados fornecido.Writes the XML Schema to the supplied data stream.

Write(Stream, XmlNamespaceManager) Write(Stream, XmlNamespaceManager) Write(Stream, XmlNamespaceManager) Write(Stream, XmlNamespaceManager)

Grava o esquema XML no Stream fornecido usando o XmlNamespaceManager especificado.Writes the XML Schema to the supplied Stream using the XmlNamespaceManager specified.

Write(TextWriter) Write(TextWriter) Write(TextWriter) Write(TextWriter)

Grava o esquema XML no TextWriter fornecido.Writes the XML Schema to the supplied TextWriter.

Write(TextWriter, XmlNamespaceManager) Write(TextWriter, XmlNamespaceManager) Write(TextWriter, XmlNamespaceManager) Write(TextWriter, XmlNamespaceManager)

Grava o esquema XML no TextWriter fornecido.Writes the XML Schema to the supplied TextWriter.

Write(XmlWriter) Write(XmlWriter) Write(XmlWriter) Write(XmlWriter)

Grava o esquema XML no XmlWriter fornecido.Writes the XML Schema to the supplied XmlWriter.

Write(XmlWriter, XmlNamespaceManager) Write(XmlWriter, XmlNamespaceManager) Write(XmlWriter, XmlNamespaceManager) Write(XmlWriter, XmlNamespaceManager)

Grava o esquema XML no XmlWriter fornecido.Writes the XML Schema to the supplied XmlWriter.

Aplica-se a

Veja também