Share via


Reading and Writing XML Schemas

The Schema Object Model (SOM) API can be used to read and write XML Schema definition language (XSD) schemas from files or other sources and build XML schemas in-memory using the classes in the System.Xml.Schema namespace that map to the structures defined in the World Wide Web Consortium (W3C) XML Schema Recommendation.

Reading and Writing XML Schemas

The XmlSchema class provides the Read and Write methods to read and write XML schemas. The Read method returns an XmlSchema object representing the XML schema and takes an optional ValidationEventHandler as a parameter to handle schema validation warnings and errors encountered while reading an XML schema.

The Write method writes XML schemas to Stream, TextWriter and XmlWriter objects and can take an optional XmlNamespaceManager object as a parameter. An XmlNamespaceManager is used to handle namespaces encountered in an XML schema. For more information about the XmlNamespaceManager class, see Manage Namespaces Using the XmlNamespaceManager.

The following code example illustrates reading and writing XML schemas from and to a file. The code example takes the example.xsd file, reads it into an XmlSchema object using the static Read method, and then writes the file to the console and a new new.xsd file. The code example also provides a ValidationEventHandler as a parameter to the static Read method to handle any schema validation warnings or errors encountered while reading the XML schema. If the ValidationEventHandler is not specified (null), no warnings or errors are reported.

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;
};

The example takes the example.xsd as input.

<?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>

See Also

Concepts

XML Schema Object Model Overview

Building XML Schemas

Traversing XML Schemas

Editing XML Schemas

Including or Importing XML Schemas

XmlSchemaSet for Schema Compilation

Post-Schema Compilation Infoset

Manage Namespaces Using the XmlNamespaceManager