Recipe 15.13. Getting Your Schema in Bulk from Existing XML FilesProblemYou 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. SolutionUse the XmlSchemaInference class to infer schema from the XML samples. The GenerateSchemaForDirectory function in Example 15-9 enumerates all of the XML files in a given directory and processes each of them using the XmlSchemaInference.InferSchema method. Once the schemas have been determined, it rolls over the collection and saves out each schema to an XSD file using a FileStream. Example 15-9. Generating an XML Schema
The GenerateSchemaForDirectory method can be called like this: // Get the directory two levels up from where we are running. DirectoryInfo di = new DirectoryInfo(@"..\.."); string dir = di.FullName; // Generate the schema. GenerateSchemaForDirectory(dir); DiscussionHaving an XSD for the XML files in an application allows for a number of things:
Using the GenerateSchemaForDirectory method can jump-start the process of developing schema for your XML, but each schema should be reviewed by the team member responsible for producing the XML. This will help to ensure that the rules as stated in the schema are correct and also to make sure that additional items like schema default values and other relationships are added. Any relationships that were not present in the example XML files would be missed by the schema generator. See AlsoSee the "XmlSchemaInference Class" and "XML Schemas (XSD) Reference" topics in the MSDN documentation. |