Reading and Writing XML Schema

The Schema Object Model (SOM) can be used to read and write XML Schema definition language (XSD) schemas from files or other sources using the XmlTextReader, XmlTextWriter, and XmlSchema classes.

The following code example illustrates reading an XML Schema from a file, Example.xsd, and printing the file to the console, then writing the schema to a new file, New.xsd.

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

Class ReadWriteSample
   Public Shared Sub Main()
      
      Try
         
         Dim reader As New XmlTextReader("Example.xsd")
         Dim myschema As XmlSchema = XmlSchema.Read(reader, Nothing)
         myschema.Write(Console.Out)
         Dim file As New FileStream("New.xsd", FileMode.Create, FileAccess.ReadWrite)
         Dim xwriter As New XmlTextWriter(file, New UTF8Encoding())
         xwriter.Formatting = Formatting.Indented
         myschema.Write(xwriter)
      
      Catch e As Exception
         Console.WriteLine(e)
      End Try
   End Sub 
End Class 
[C#]
using System.IO; 
using System;
using System.Xml;  
using System.Xml.Schema;
using System.Text; 

class ReadWriteSample {
   
public static void Main() {
 
   try{ 

   XmlTextReader reader = new XmlTextReader ("Example.xsd");
   XmlSchema myschema = XmlSchema.Read(reader, null); 
   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);
    }
  }
}

The following XML Schema outlines the contents of the input file, Example.xsd.

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

XML Schema Object Model (SOM) | XmlSchema Class