Share via


Lecture et écroture de schémas XML

L'API Modèle Objet du schéma (SOM) peut permettre de lire et écrire des schémas de langage XSD (XML Schema Definition) dans des fichiers ou d'autres sources et de générer un cache de schéma XML à l'aide des classes de l'espace de noms System.Xml.Schema correspondant aux structures définies dans la recommandation du W3C (World Wide Web Consortium) sur les schémas XML.

Lecture et écriture de schémas XML

La classe XmlSchema fournit les méthodes Read et Write pour lire et écrire des schémas XML. La méthode Read retourne un objet XmlSchema représentant le schéma XML et prend un objet ValidationEventHandler facultatif comme paramètre pour traiter les avertissements et erreurs de validation de schéma rencontrées lors de la lecture d'un schéma XML.

La méthode Write écrit des schémas XML dans des objets Stream, TextWriter et XmlWriter et peut prendre un XmlNamespaceManager facultatif comme paramètre. Un objet XmlNamespaceManager permet de traiter les espaces de noms rencontrés dans un schéma XML. Pour plus d'informations sur la classe XmlNamespaceManager, voir Gestion des espaces de noms à l'aide de XmlNamespaceManager.

L'exemple de code suivant illustre la lecture et l'écriture de schémas XML à partir de et vers un fichier. Il prend le fichier example.xsd, le lit dans un objet XmlSchema à l'aide de la méthode static Read, puis l'écrit dans la console et dans un nouveau fichier new.xsd. Il fournit également un objet ValidationEventHandler comme paramètre à la méthode static Read pour traiter les avertissements ou erreurs de validation de schéma rencontrés pendant la lecture du schéma XML. Si l'objet ValidationEventHandler n'est pas spécifié (null), aucun avertissement ou aucune erreur n'est signalée.

Imports System
Imports System.IO
Imports System.Text
Imports System.Xml
Imports System.Xml.Schema

Class XmlSchemaReadWriteExample

    Shared Sub Main()
        Try
            Dim reader As XmlTextReader = New XmlTextReader("example.xsd")
            Dim myschema As XmlSchema = XmlSchema.Read(reader, AddressOf ValidationCallback)
            myschema.Write(Console.Out)

            Dim file As FileStream = New FileStream("new.xsd", FileMode.Create, FileAccess.ReadWrite)
            Dim xwriter As XmlTextWriter = New XmlTextWriter(file, New UTF8Encoding())
            xwriter.Formatting = Formatting.Indented
            myschema.Write(xwriter)
        Catch e As Exception
            Console.WriteLine(e)
        End Try
    End Sub

    Shared Sub ValidationCallback(ByVal sender As Object, ByVal args As ValidationEventArgs)
        If args.Severity = XmlSeverityType.Warning Then
            Console.Write("WARNING: ")
        Else
            If args.Severity = XmlSeverityType.Error Then
                Console.Write("ERROR: ")
            End If
        End If
        Console.WriteLine(args.Message)
    End Sub
End Class
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaReadWriteExample
{
    static void Main()
    {
        try
        {
            XmlTextReader reader = new XmlTextReader("example.xsd");
            XmlSchema myschema = XmlSchema.Read(reader, ValidationCallback);
            myschema.Write(Console.Out);
            FileStream file = new FileStream("new.xsd", FileMode.Create, FileAccess.ReadWrite);
            XmlTextWriter xwriter = new XmlTextWriter(file, new UTF8Encoding());
            xwriter.Formatting = Formatting.Indented;
            myschema.Write(xwriter);
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }
    }

    static void ValidationCallback(object sender, ValidationEventArgs args)
    {
        if (args.Severity == XmlSeverityType.Warning)
            Console.Write("WARNING: ");
        else if (args.Severity == XmlSeverityType.Error)
            Console.Write("ERROR: ");

        Console.WriteLine(args.Message);
    }
}
#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Xml;
using namespace System::Xml::Schema;

ref class XmlSchemaReadWriteExample
{
public:

    static void Main()
    {
        try
        {
            XmlTextReader^ reader = gcnew XmlTextReader("example.xsd");
            ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationCallback);
            XmlSchema^ myschema = XmlSchema::Read(reader, eventHandler);
            myschema->Write(Console::Out);
            FileStream^ file = gcnew FileStream("new.xsd", FileMode::Create, FileAccess::ReadWrite);
            XmlTextWriter^ xwriter = gcnew XmlTextWriter(file, gcnew UTF8Encoding());
            xwriter->Formatting = Formatting::Indented;
            myschema->Write(xwriter);
        }
        catch(Exception^ e)
        {
            Console::WriteLine(e);
        }
    }

    static void ValidationCallback(Object^ sender, ValidationEventArgs^ args)
    {
        if (args->Severity == XmlSeverityType::Warning)
            Console::Write("WARNING: ");
        else if (args->Severity == XmlSeverityType::Error)
            Console::Write("ERROR: ");

        Console::WriteLine(args->Message);
    }
};

int main()
{
    XmlSchemaReadWriteExample::Main();
    return 0;
};

L'exemple prend le fichier example.xsd comme entrée.

<?xml version="1.0"?>
<xs:schema id="play" targetNamespace="http://tempuri.org/play.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/play.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name='myShoeSize'>
        <xs:complexType>
            <xs:simpleContent>
                <xs:extension base='xs:decimal'>
                    <xs:attribute name='sizing' type='xs:string' />
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>
</xs:schema>

Voir aussi

Concepts

Vue d'ensemble du Modèle Objet du schéma XML

Création de schémas XML

Traversée de schémas XML

Modification de schémas XML

Inclusion ou importation de schémas XML

XmlSchemaSet pour la compilation de schémas

Jeu d'informations de post-compilation de schéma

Gestion des espaces de noms à l'aide de XmlNamespaceManager