Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

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.

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.

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

class XmlSchemaReadWriteExample
    static void Main()
            XmlTextReader reader = new XmlTextReader("example.xsd");
            XmlSchema myschema = XmlSchema.Read(reader, ValidationCallback);
            FileStream file = new FileStream("new.xsd", FileMode.Create, FileAccess.ReadWrite);
            XmlTextWriter xwriter = new XmlTextWriter(file, new UTF8Encoding());
            xwriter.Formatting = Formatting.Indented;
        catch(Exception 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: ");


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:extension base='xs:decimal'>
                    <xs:attribute name='sizing' type='xs:string' />
© 2015 Microsoft