Поделиться через


XmlSchemaProviderAttribute Класс

Определение

При применении к типу сохраняет имя статического метода типа, возвращающего схему XML и XmlQualifiedName (или XmlSchemaType для анонимных типов), которая управляет сериализацией типа.

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
Наследование
XmlSchemaProviderAttribute
Атрибуты

Примеры

В следующем примере применяется XmlSchemaProviderAttribute класс на стороне сервера. При вызове метод с MethodName именем свойства создает схему. Эта простая реализация считывает существующую схему с диска. Однако при необходимости можно создать настраиваемую схему, используя типы, найденные System.Xml.Schema в пространстве имен.

[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

Комментарии

Основной целью этого XmlSchemaProviderAttribute класса является включение XmlSchemaExporter возврата схемы при запросе средства языка описания веб-служб (WSDL.exe) или при использовании функции добавления веб-ссылки Visual Studio. Вы можете управлять фактической схемой для типа в статическом методе.

Замечание

Целевой класс атрибута должен реализовать IXmlSerializable интерфейс.

Свойство MethodName возвращает имя статического метода с помощью отражения. Метод, который должен быть реализован, должен принимать один параметр, объект, XmlSchemaSet который метод заполняет XmlSchema объектом. Метод также должен возвращать объект, определяющий XmlQualifiedName тип данных.

Возврат анонимных типов

Анонимный сложный тип не может быть создан с помощью метода, который возвращается XmlQualifiedName. Так как анонимный тип не имеет имени, и вы не можете добавить анонимный тип в схему, анонимный тип должен быть возвращен как .XmlSchemaType

Конструкторы

Имя Описание
XmlSchemaProviderAttribute(String)

Инициализирует новый экземпляр XmlSchemaProviderAttribute класса, принимая имя статического метода, предоставляющего xml-схему типа.

Свойства

Имя Описание
IsAny

Возвращает или задает значение, определяющее, является ли целевой класс подстановочным знаком или что схема класса содержит только xs:any элемент.

MethodName

Возвращает имя статического метода, который предоставляет xml-схему типа и имя типа данных схемы XML.

TypeId

При реализации в производном классе получает уникальный идентификатор для этого Attribute.

(Унаследовано от Attribute)

Методы

Имя Описание
Equals(Object)

Возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

(Унаследовано от Attribute)
GetHashCode()

Возвращает хэш-код для этого экземпляра.

(Унаследовано от Attribute)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
IsDefaultAttribute()

При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса.

(Унаследовано от Attribute)
Match(Object)

При переопределении в производном классе возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

(Унаследовано от Attribute)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

Имя Описание
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации.

(Унаследовано от Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Извлекает сведения о типе объекта, который можно использовать для получения сведений о типе для интерфейса.

(Унаследовано от Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к свойствам и методам, предоставляемым объектом.

(Унаследовано от Attribute)

Применяется к

См. также раздел