Created
October 28, 2014 06:17
-
-
Save larsw/b262b6ff1ca4cc770826 to your computer and use it in GitHub Desktop.
XsdFs.fs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module XsdFs.Program | |
| open System; | |
| open System.IO; | |
| open System.Collections.Generic; | |
| open System.Reflection; | |
| open System.Text; | |
| open System.Xml; | |
| open System.Xml.Serialization; | |
| open System.Xml.Schema; | |
| open System.CodeDom; | |
| open System.CodeDom.Compiler; | |
| open FSharp.Compiler.CodeDom; | |
| open Microsoft.CSharp; | |
| let XsdToClasses(xsdPath) : string = | |
| // let path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); | |
| // let xsdPath = Path.Combine(path, xsdFileName); | |
| // load the xsd | |
| use stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read) | |
| let xsd = XmlSchema.Read(stream, null); | |
| printfn "xsd.IsCompiled %A" xsd.IsCompiled | |
| let xsds = new XmlSchemas(); | |
| xsds.Add(xsd) |> ignore | |
| xsds.Compile(null, true); | |
| let schemaImporter = new XmlSchemaImporter(xsds); | |
| // create the codedom | |
| let codeNamespace = new CodeNamespace("Generated"); | |
| let codeExporter = new XmlCodeExporter(codeNamespace); | |
| let maps = List<XmlTypeMapping>() | |
| Seq.cast xsd.SchemaTypes.Values |> | |
| Seq.iter (fun (x:XmlSchemaType) -> maps.Add(schemaImporter.ImportSchemaType(x.QualifiedName))) | |
| Seq.cast xsd.Elements.Values |> | |
| Seq.iter (fun (x:XmlSchemaElement) -> maps.Add(schemaImporter.ImportTypeMapping(x.QualifiedName))) | |
| for map in maps do | |
| codeExporter.ExportTypeMapping(map); | |
| // Check for invalid characters in identifiers | |
| CodeGenerator.ValidateIdentifiers(codeNamespace); | |
| let codeProvider = new FSharpCleanCodeProvider(); | |
| use writer = new StringWriter() | |
| codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); | |
| writer.GetStringBuilder().ToString(); | |
| [<EntryPoint>] | |
| let main argv = | |
| if (Array.length argv) = 0 then | |
| -1 | |
| else | |
| let code = XsdToClasses argv.[0] | |
| printfn "%s" code | |
| 0 // return an integer exit code | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment