XmlSchemaProviderAttribute Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Quando aplicado a um tipo, armazena o nome de um método estático do tipo que devolve um esquema XML e um XmlQualifiedName (ou XmlSchemaType para tipos anónimos) que controla a serialização do tipo.
public ref class XmlSchemaProviderAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface | System.AttributeTargets.Struct)]
public sealed class XmlSchemaProviderAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface | System.AttributeTargets.Struct)>]
type XmlSchemaProviderAttribute = class
inherit Attribute
Public NotInheritable Class XmlSchemaProviderAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O exemplo seguinte aplica-se XmlSchemaProviderAttribute a uma classe do lado do servidor. Quando invocado, o método nomeado pela MethodName propriedade cria o esquema. Esta implementação simples lê um esquema existente do disco. No entanto, também pode criar um esquema personalizado, se necessário, usando os tipos encontrados no System.Xml.Schema namespace.
[XmlSchemaProvider("MySchema")]
public class SongStream : IXmlSerializable
{
private const string ns = "http://demos.Contoso.com/webservices";
private string filePath;
public SongStream() { }
public SongStream(string filePath)
{
this.filePath = filePath;
}
// This is the method named by the XmlSchemaProviderAttribute applied to the type.
public static XmlQualifiedName MySchema(XmlSchemaSet xs)
{
// This method is called by the framework to get the schema for this type.
// We return an existing schema from disk.
XmlSerializer schemaSerializer = new XmlSerializer(typeof(XmlSchema));
string xsdPath = null;
// NOTE: replace the string with your own path.
xsdPath = System.Web.HttpContext.Current.Server.MapPath("SongStream.xsd");
XmlSchema s = (XmlSchema)schemaSerializer.Deserialize(
new XmlTextReader(xsdPath), null);
xs.XmlResolver = new XmlUrlResolver();
xs.Add(s);
return new XmlQualifiedName("songStream", ns);
}
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
// This is the chunking code.
// ASP.NET buffering must be turned off for this to work.
int bufferSize = 4096;
char[] songBytes = new char[bufferSize];
FileStream inFile = File.Open(this.filePath, FileMode.Open, FileAccess.Read);
long length = inFile.Length;
// Write the file name.
writer.WriteElementString("fileName", ns, Path.GetFileNameWithoutExtension(this.filePath));
// Write the size.
writer.WriteElementString("size", ns, length.ToString());
// Write the song bytes.
writer.WriteStartElement("song", ns);
StreamReader sr = new StreamReader(inFile, true);
int readLen = sr.Read(songBytes, 0, bufferSize);
while (readLen > 0)
{
writer.WriteStartElement("chunk", ns);
writer.WriteChars(songBytes, 0, readLen);
writer.WriteEndElement();
writer.Flush();
readLen = sr.Read(songBytes, 0, bufferSize);
}
writer.WriteEndElement();
inFile.Close();
}
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
throw new System.NotImplementedException();
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
throw new System.NotImplementedException();
}
}
<XmlSchemaProvider("MySchema")> _
Public Class SongStream
Implements IXmlSerializable
Private Const ns As String = "http://demos.Contoso.com/webservices"
Private filePath As String
Public Sub New()
End Sub
Public Sub New(ByVal filePath As String)
Me.filePath = filePath
End Sub
' This is the method named by the XmlSchemaProviderAttribute applied to the type.
Public Shared Function MySchema(ByVal xs As XmlSchemaSet) As XmlQualifiedName
' This method is called by the framework to get the schema for this type.
' We return an existing schema from disk.
Dim schemaSerializer As New XmlSerializer(GetType(XmlSchema))
Dim xsdPath As String = Nothing
' NOTE: replace SongStream.xsd with your own schema file.
xsdPath = System.Web.HttpContext.Current.Server.MapPath("SongStream.xsd")
Dim s As XmlSchema = CType(schemaSerializer.Deserialize(New XmlTextReader(xsdPath)), XmlSchema)
xs.XmlResolver = New XmlUrlResolver()
xs.Add(s)
Return New XmlQualifiedName("songStream", ns)
End Function
Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml
' This is the chunking code.
' ASP.NET buffering must be turned off for this to work.
Dim bufferSize As Integer = 4096
Dim songBytes(bufferSize) As Char
Dim inFile As FileStream = File.Open(Me.filePath, FileMode.Open, FileAccess.Read)
Dim length As Long = inFile.Length
' Write the file name.
writer.WriteElementString("fileName", ns, Path.GetFileNameWithoutExtension(Me.filePath))
' Write the size.
writer.WriteElementString("size", ns, length.ToString())
' Write the song bytes.
writer.WriteStartElement("song", ns)
Dim sr As New StreamReader(inFile, True)
Dim readLen As Integer = sr.Read(songBytes, 0, bufferSize)
While readLen > 0
writer.WriteStartElement("chunk", ns)
writer.WriteChars(songBytes, 0, readLen)
writer.WriteEndElement()
writer.Flush()
readLen = sr.Read(songBytes, 0, bufferSize)
End While
writer.WriteEndElement()
inFile.Close()
End Sub
Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema
Throw New System.NotImplementedException()
End Function
Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml
Throw New System.NotImplementedException()
End Sub
End Class
Observações
O principal objetivo do XmlSchemaProviderAttribute é permitir que a classe XmlSchemaExporter devolva um esquema quando consultado pela ferramenta Web Services Description Language (WSDL.exe), ou ao utilizar a funcionalidade Add Web Reference do Visual Studio. Podes controlar o esquema real para o tipo no método estático.
Note
A classe alvo do atributo deve implementar a IXmlSerializable interface.
A MethodName propriedade devolve o nome de um método estático através da reflexão. O método, que deve ser implementado, deve tomar um único parâmetro, um XmlSchemaSet objeto, que o método preenche com um XmlSchema objeto. O método deve também devolver um XmlQualifiedName objeto que identifique o tipo de dado.
Retorno de Tipos Anónimos
Um tipo complexo anónimo não pode ser criado usando um método que devolve XmlQualifiedName. Como um tipo anónimo não tem nome, e não se pode adicionar um tipo anónimo a um esquema, o tipo anónimo deve ser devolvido como um XmlSchemaType.
Construtores
| Name | Description |
|---|---|
| XmlSchemaProviderAttribute(String) |
Inicializa uma nova instância da XmlSchemaProviderAttribute classe, tomando o nome do método estático que fornece o esquema XML do tipo. |
Propriedades
| Name | Description |
|---|---|
| IsAny |
Recebe ou define um valor que determina se a classe alvo é um coringa, ou se o esquema da classe contém apenas um |
| MethodName |
Obtém o nome do método estático que fornece o esquema XML do tipo e o nome do seu tipo de dado XML Schema. |
| TypeId |
Quando implementado numa classe derivada, obtém um identificador único para esta Attribute. (Herdado de Attribute) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| GetHashCode() |
Devolve o código de hash para esta instância. (Herdado de Attribute) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsDefaultAttribute() |
Quando sobrescrito numa classe derivada, indica se o valor desta instância é o valor padrão para a classe derivada. (Herdado de Attribute) |
| Match(Object) |
Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera o número de interfaces de informações de tipo que um objeto fornece (0 ou 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acesso a propriedades e métodos expostos por um objeto. (Herdado de Attribute) |