Creating Schema from Xml file

Here is a code snippet that creates a simple schema file from an
Xml file. It uses XmlSchemaInference class (available from .net 2.0+)
to inferschema from an xml file.

        XmlReader reader = XmlReader.Create(@"c:\binu\customer.xml");

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        XmlSchemaInference schema = new XmlSchemaInference();

        schemaSet = schema.InferSchema(reader);

        TextWriter writer = new StreamWriter(@"c:\binu\customer.xsd");

        foreach (XmlSchema s in schemaSet.Schemas())




Sample Xml file used:


<Customer CustomerName="Maria Anders" Country="Germany"/>

<Customer CustomerName="Ana Trujillo" Country="Russia"/>

<Customer CustomerName="Antonio Moreno" Country="Spain"/>

<Customer CustomerName="Thomas Hardy" Country="United Kingdom"/>

<Customer CustomerName="Maria Anders" Country="Holand"/>

<Customer CustomerName="Christina Berglund" Country="Sweden"/>



<?xml version="1.0" encoding="utf-8"?>

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="">

  <xs:element name="Customers">



        <xs:element maxOccurs="unbounded" name="Customer">


            <xs:attribute name="CustomerName" type="xs:string" use="required" />

            <xs:attribute name="Country" type="xs:string" use="required" />







Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s