Skip to main content

Generates XML schema files from a directory of XML files.

public static void TestBulkSchema()
{
    DirectoryInfo di = new DirectoryInfo(@"..\..");
    string dir = di.FullName;
    GenerateSchemasForDirectory(dir);
}

public static void GenerateSchemasForFile(string file)
{
    // set up a reader for the file
    using (XmlReader reader = XmlReader.Create(file))
    {
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        XmlSchemaInference schemaInference = new XmlSchemaInference();

        // get the schema
        schemaSet = schemaInference.InferSchema(reader);

        string schemaPath = string.Empty;
        foreach (XmlSchema schema in schemaSet.Schemas())
        {
            // make schema file path and write it out
            schemaPath = Path.GetDirectoryName(file) + @"\" + Path.GetFileNameWithoutExtension(file) + ".xsd";
            using (FileStream fs = new FileStream(schemaPath, FileMode.OpenOrCreate))
            {
                schema.Write(fs);
            }
        }
    }
}

public static void GenerateSchemasForDirectory(string dir)
{
    // make sure the directory exists
    if (Directory.Exists(dir))
    {
        // get the files in the directory
        string[] files = Directory.GetFiles(dir, "*.xml");
        foreach (string file in files)
        {
            GenerateSchemasForFile(file);
        }
    }
}