
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
872
|
Chapter 15: XML
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);
Discussion
Having an XSD for the XML files in an application allows for a number of things:
1. Validation of XML presented to the system
2. Documentation of the semantics of the data
3. Programmatic discovery of the data structure through XML reading methods
Example 15-9. Generating an XML Schema
public static void GenerateSchemaForDirectory(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)
{
// 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 = "";
foreach (XmlSchema schema in schemaSet.Schemas( ))
{
// Make schema file path.
schemaPath = Path.GetDirectoryName(file) + @"\" +
Path.GetFileNameWithoutExtension(file) + ".xsd";
using (FileStream fs ...