15.13. Getting Your Schemas in Bulk from Existing XML Files
Problem
You have come on to a new project in which XML was used for data transmission, but the programmers who came before you didn't use an XSD for one reason or another. You need to generate beginning schema files for each of the XML examples.
Solution
Use the XmlSchemaInference class to infer schema from the XML samples. The GenerateSchemasForDirectory function in Example 15-12 enumerates all of the XML files in a given directory and processes each of them using the GenerateSchemasForFile method. GenerateSchemasForFile uses the XmlSchemaInference.InferSchema method to get the schemas for the given XML file. Once the schemas have been determined, GenerateSchemasForFile rolls over the collection and saves out each schema to an XSD file using a FileStream.
Example 15-12. Generating an XML Schema
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); } ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access