Gokul's Blog

Generate XSD for a XML file

Leave a comment

Original Link: http://www.gibmonks.com/c_sharp/csharpckbk2-CHP-15-SECT-13.html

[sourceode language=”csharp”]
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 =
new FileStream(schemaPath, FileMode.OpenOrCreate))
{
schema.Write(fs);
}
}
}
}
}
}
[/sourcecode]

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s