5 people like it.
Like the snippet!
XSD Class Generator
This can be used to generate F# code from an XSD schema. Similar to xsd.exe, this can be wrapped in a console application and used for generator XML or SOAP service clients to facilitate serialization/deserialization of XML into objects.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
|
open FSharp.Compiler.CodeDom
open System.CodeDom
open System.CodeDom.Compiler
open System.IO
open System.Linq
open System.Xml
open System.Xml.Schema
open System.Xml.Serialization
module XsdGenerator =
let private printValidationError step =
ValidationEventHandler(fun _ error ->
if error.Severity = XmlSeverityType.Error
then printfn "ERROR -- %s: %s" step error.Message
else printfn "Warning -- %s: %s" step error.Message)
let importTypes (xsd: XmlSchema) =
let schemas = XmlSchemas()
schemas.Add(xsd) |> ignore
schemas.Compile(printValidationError "Compiling XSD", true)
let importer = XmlSchemaImporter(schemas)
[
for schemaType in xsd.SchemaTypes.Values.OfType<XmlSchemaType>() do
yield importer.ImportSchemaType(schemaType.QualifiedName)
for schemaElement in xsd.Elements.Values.OfType<XmlSchemaElement>() do
yield importer.ImportTypeMapping(schemaElement.QualifiedName)
]
let readXsd (xsdFile: FileInfo) =
use inputStream = xsdFile.OpenRead()
use schemaReader = new XmlTextReader(inputStream)
XmlSchema.Read(schemaReader, printValidationError "Reading XSD")
let exportCode (``namespace``: string option) (typeMappings: XmlTypeMapping list) =
let codeNamespace = ``namespace`` |> Option.defaultValue "Xsd.Generated" |> CodeNamespace
let exporter = XmlCodeExporter(codeNamespace)
typeMappings |> List.iter exporter.ExportTypeMapping
codeNamespace
let validateCode (codeNamespace: CodeNamespace) =
codeNamespace.Types.OfType<CodeTypeDeclaration>()
|> Seq.iter (fun t ->
let xmlType = t.CustomAttributes.OfType<CodeAttributeDeclaration>() |> Seq.tryFind (fun a -> a.Name = "System.Xml.Serialization.XmlTypeAttribute")
t.CustomAttributes.Clear()
xmlType |> Option.iter (t.CustomAttributes.Add >> ignore))
CodeGenerator.ValidateIdentifiers(codeNamespace)
codeNamespace
let saveToFile (outputFile: FileInfo) (codeNamespace: CodeNamespace) =
use codeProvider = new FSharpCodeProvider()
use writer = new StreamWriter(outputFile.FullName, false)
let options = CodeGeneratorOptions(VerbatimOrder = true)
codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, options)
let generateClasses ``namespace`` outputFile xsdFile =
xsdFile
|> readXsd
|> importTypes
|> exportCode ``namespace``
|> validateCode
|> saveToFile outputFile
|
Multiple items
namespace FSharp
--------------------
namespace Microsoft.FSharp
namespace FSharp.Compiler
namespace FSharp.Compiler.CodeDom
namespace System
namespace System.CodeDom
namespace System.CodeDom.Compiler
namespace System.IO
namespace System.Linq
namespace System.Xml
namespace System.Xml.Schema
namespace System.Xml.Serialization
module XsdGenerator
from Script
val private printValidationError : step:string -> ValidationEventHandler
Full name: Script.XsdGenerator.printValidationError
val step : string
type ValidationEventHandler =
delegate of obj * ValidationEventArgs -> unit
Full name: System.Xml.Schema.ValidationEventHandler
val error : ValidationEventArgs
property ValidationEventArgs.Severity: XmlSeverityType
type XmlSeverityType =
| Error = 0
| Warning = 1
Full name: System.Xml.Schema.XmlSeverityType
field XmlSeverityType.Error = 0
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
property ValidationEventArgs.Message: string
val importTypes : xsd:XmlSchema -> XmlTypeMapping list
Full name: Script.XsdGenerator.importTypes
val xsd : XmlSchema
Multiple items
type XmlSchema =
inherit XmlSchemaObject
new : unit -> XmlSchema
member AttributeFormDefault : XmlSchemaForm with get, set
member AttributeGroups : XmlSchemaObjectTable
member Attributes : XmlSchemaObjectTable
member BlockDefault : XmlSchemaDerivationMethod with get, set
member Compile : validationEventHandler:ValidationEventHandler -> unit + 1 overload
member ElementFormDefault : XmlSchemaForm with get, set
member Elements : XmlSchemaObjectTable
member FinalDefault : XmlSchemaDerivationMethod with get, set
member Groups : XmlSchemaObjectTable
...
Full name: System.Xml.Schema.XmlSchema
--------------------
type XmlSchemaAttribute =
inherit XmlSchemaAnnotated
new : unit -> XmlSchemaAttribute
member AttributeSchemaType : XmlSchemaSimpleType
member AttributeType : obj
member DefaultValue : string with get, set
member FixedValue : string with get, set
member Form : XmlSchemaForm with get, set
member Name : string with get, set
member QualifiedName : XmlQualifiedName
member RefName : XmlQualifiedName with get, set
member SchemaType : XmlSchemaSimpleType with get, set
...
Full name: System.Xml.Schema.XmlSchemaAttribute
--------------------
XmlSchema() : unit
--------------------
XmlSchemaAttribute() : unit
val schemas : XmlSchemas
Multiple items
type XmlSchemas =
inherit CollectionBase
new : unit -> XmlSchemas
member Add : schema:XmlSchema -> int + 2 overloads
member AddReference : schema:XmlSchema -> unit
member Compile : handler:ValidationEventHandler * fullCompile:bool -> unit
member Contains : schema:XmlSchema -> bool + 1 overload
member CopyTo : array:XmlSchema[] * index:int -> unit
member Find : name:XmlQualifiedName * type:Type -> obj
member GetSchemas : ns:string -> IList
member IndexOf : schema:XmlSchema -> int
member Insert : index:int * schema:XmlSchema -> unit
...
Full name: System.Xml.Serialization.XmlSchemas
--------------------
XmlSchemas() : unit
XmlSchemas.Add(schemas: XmlSchemas) : unit
XmlSchemas.Add(schema: XmlSchema) : int
XmlSchemas.Add(schema: XmlSchema, baseUri: System.Uri) : int
val ignore : value:'T -> unit
Full name: Microsoft.FSharp.Core.Operators.ignore
XmlSchemas.Compile(handler: ValidationEventHandler, fullCompile: bool) : unit
val importer : XmlSchemaImporter
Multiple items
type XmlSchemaImporter =
inherit SchemaImporter
new : schemas:XmlSchemas -> XmlSchemaImporter + 4 overloads
member ImportAnyType : typeName:XmlQualifiedName * elementName:string -> XmlMembersMapping
member ImportDerivedTypeMapping : name:XmlQualifiedName * baseType:Type -> XmlTypeMapping + 1 overload
member ImportMembersMapping : name:XmlQualifiedName -> XmlMembersMapping + 3 overloads
member ImportSchemaType : typeName:XmlQualifiedName -> XmlTypeMapping + 2 overloads
member ImportTypeMapping : name:XmlQualifiedName -> XmlTypeMapping
Full name: System.Xml.Serialization.XmlSchemaImporter
--------------------
XmlSchemaImporter(schemas: XmlSchemas) : unit
XmlSchemaImporter(schemas: XmlSchemas, typeIdentifiers: CodeIdentifiers) : unit
XmlSchemaImporter(schemas: XmlSchemas, typeIdentifiers: CodeIdentifiers, options: CodeGenerationOptions) : unit
XmlSchemaImporter(schemas: XmlSchemas, options: CodeGenerationOptions, context: ImportContext) : unit
XmlSchemaImporter(schemas: XmlSchemas, options: CodeGenerationOptions, codeProvider: CodeDomProvider, context: ImportContext) : unit
val schemaType : XmlSchemaType
property XmlSchema.SchemaTypes: XmlSchemaObjectTable
property XmlSchemaObjectTable.Values: System.Collections.ICollection
(extension) System.Collections.IEnumerable.OfType<'TResult>() : System.Collections.Generic.IEnumerable<'TResult>
Multiple items
type XmlSchemaType =
inherit XmlSchemaAnnotated
new : unit -> XmlSchemaType
member BaseSchemaType : obj
member BaseXmlSchemaType : XmlSchemaType
member Datatype : XmlSchemaDatatype
member DerivedBy : XmlSchemaDerivationMethod
member Final : XmlSchemaDerivationMethod with get, set
member FinalResolved : XmlSchemaDerivationMethod
member IsMixed : bool with get, set
member Name : string with get, set
member QualifiedName : XmlQualifiedName
...
Full name: System.Xml.Schema.XmlSchemaType
--------------------
XmlSchemaType() : unit
XmlSchemaImporter.ImportSchemaType(typeName: XmlQualifiedName) : XmlTypeMapping
XmlSchemaImporter.ImportSchemaType(typeName: XmlQualifiedName, baseType: System.Type) : XmlTypeMapping
XmlSchemaImporter.ImportSchemaType(typeName: XmlQualifiedName, baseType: System.Type, baseTypeCanBeIndirect: bool) : XmlTypeMapping
property XmlSchemaType.QualifiedName: XmlQualifiedName
val schemaElement : XmlSchemaElement
property XmlSchema.Elements: XmlSchemaObjectTable
Multiple items
type XmlSchemaElement =
inherit XmlSchemaParticle
new : unit -> XmlSchemaElement
member Block : XmlSchemaDerivationMethod with get, set
member BlockResolved : XmlSchemaDerivationMethod
member Constraints : XmlSchemaObjectCollection
member DefaultValue : string with get, set
member ElementSchemaType : XmlSchemaType
member ElementType : obj
member Final : XmlSchemaDerivationMethod with get, set
member FinalResolved : XmlSchemaDerivationMethod
member FixedValue : string with get, set
...
Full name: System.Xml.Schema.XmlSchemaElement
--------------------
XmlSchemaElement() : unit
XmlSchemaImporter.ImportTypeMapping(name: XmlQualifiedName) : XmlTypeMapping
property XmlSchemaElement.QualifiedName: XmlQualifiedName
val readXsd : xsdFile:FileInfo -> XmlSchema
Full name: Script.XsdGenerator.readXsd
val xsdFile : FileInfo
Multiple items
type FileInfo =
inherit FileSystemInfo
new : fileName:string -> FileInfo
member AppendText : unit -> StreamWriter
member CopyTo : destFileName:string -> FileInfo + 1 overload
member Create : unit -> FileStream
member CreateText : unit -> StreamWriter
member Decrypt : unit -> unit
member Delete : unit -> unit
member Directory : DirectoryInfo
member DirectoryName : string
member Encrypt : unit -> unit
...
Full name: System.IO.FileInfo
--------------------
FileInfo(fileName: string) : unit
val inputStream : FileStream
FileInfo.OpenRead() : FileStream
val schemaReader : XmlTextReader
Multiple items
type XmlTextReader =
inherit XmlReader
new : input:Stream -> XmlTextReader + 11 overloads
member AttributeCount : int
member BaseURI : string
member CanReadBinaryContent : bool
member CanReadValueChunk : bool
member CanResolveEntity : bool
member Close : unit -> unit
member Depth : int
member DtdProcessing : DtdProcessing with get, set
member EOF : bool
...
Full name: System.Xml.XmlTextReader
--------------------
XmlTextReader(input: Stream) : unit
(+0 other overloads)
XmlTextReader(input: TextReader) : unit
(+0 other overloads)
XmlTextReader(url: string) : unit
(+0 other overloads)
XmlTextReader(url: string, input: Stream) : unit
(+0 other overloads)
XmlTextReader(input: Stream, nt: XmlNameTable) : unit
(+0 other overloads)
XmlTextReader(url: string, input: TextReader) : unit
(+0 other overloads)
XmlTextReader(input: TextReader, nt: XmlNameTable) : unit
(+0 other overloads)
XmlTextReader(url: string, nt: XmlNameTable) : unit
(+0 other overloads)
XmlTextReader(url: string, input: Stream, nt: XmlNameTable) : unit
(+0 other overloads)
XmlTextReader(url: string, input: TextReader, nt: XmlNameTable) : unit
(+0 other overloads)
XmlSchema.Read(reader: XmlReader, validationEventHandler: ValidationEventHandler) : XmlSchema
XmlSchema.Read(stream: Stream, validationEventHandler: ValidationEventHandler) : XmlSchema
XmlSchema.Read(reader: TextReader, validationEventHandler: ValidationEventHandler) : XmlSchema
val exportCode : namespace:string option -> typeMappings:XmlTypeMapping list -> CodeNamespace
Full name: Script.XsdGenerator.exportCode
Multiple items
val string : value:'T -> string
Full name: Microsoft.FSharp.Core.Operators.string
--------------------
type string = System.String
Full name: Microsoft.FSharp.Core.string
type 'T option = Option<'T>
Full name: Microsoft.FSharp.Core.option<_>
val typeMappings : XmlTypeMapping list
type XmlTypeMapping =
inherit XmlMapping
member TypeFullName : string
member TypeName : string
member XsdTypeName : string
member XsdTypeNamespace : string
Full name: System.Xml.Serialization.XmlTypeMapping
type 'T list = List<'T>
Full name: Microsoft.FSharp.Collections.list<_>
val codeNamespace : CodeNamespace
module Option
from Microsoft.FSharp.Core
Multiple items
type CodeNamespace =
inherit CodeObject
new : unit -> CodeNamespace + 1 overload
member Comments : CodeCommentStatementCollection
member Imports : CodeNamespaceImportCollection
member Name : string with get, set
member Types : CodeTypeDeclarationCollection
event PopulateComments : EventHandler
event PopulateImports : EventHandler
event PopulateTypes : EventHandler
Full name: System.CodeDom.CodeNamespace
--------------------
CodeNamespace() : unit
CodeNamespace(name: string) : unit
val exporter : XmlCodeExporter
Multiple items
type XmlCodeExporter =
inherit CodeExporter
new : codeNamespace:CodeNamespace -> XmlCodeExporter + 4 overloads
member AddMappingMetadata : metadata:CodeAttributeDeclarationCollection * mapping:XmlTypeMapping * ns:string -> unit + 2 overloads
member ExportMembersMapping : xmlMembersMapping:XmlMembersMapping -> unit
member ExportTypeMapping : xmlTypeMapping:XmlTypeMapping -> unit
Full name: System.Xml.Serialization.XmlCodeExporter
--------------------
XmlCodeExporter(codeNamespace: CodeNamespace) : unit
XmlCodeExporter(codeNamespace: CodeNamespace, codeCompileUnit: CodeCompileUnit) : unit
XmlCodeExporter(codeNamespace: CodeNamespace, codeCompileUnit: CodeCompileUnit, options: CodeGenerationOptions) : unit
XmlCodeExporter(codeNamespace: CodeNamespace, codeCompileUnit: CodeCompileUnit, options: CodeGenerationOptions, mappings: System.Collections.Hashtable) : unit
XmlCodeExporter(codeNamespace: CodeNamespace, codeCompileUnit: CodeCompileUnit, codeProvider: CodeDomProvider, options: CodeGenerationOptions, mappings: System.Collections.Hashtable) : unit
Multiple items
module List
from Microsoft.FSharp.Collections
--------------------
type List<'T> =
| ( [] )
| ( :: ) of Head: 'T * Tail: 'T list
interface IEnumerable
interface IEnumerable<'T>
member GetSlice : startIndex:int option * endIndex:int option -> 'T list
member Head : 'T
member IsEmpty : bool
member Item : index:int -> 'T with get
member Length : int
member Tail : 'T list
static member Cons : head:'T * tail:'T list -> 'T list
static member Empty : 'T list
Full name: Microsoft.FSharp.Collections.List<_>
val iter : action:('T -> unit) -> list:'T list -> unit
Full name: Microsoft.FSharp.Collections.List.iter
XmlCodeExporter.ExportTypeMapping(xmlTypeMapping: XmlTypeMapping) : unit
val validateCode : codeNamespace:CodeNamespace -> CodeNamespace
Full name: Script.XsdGenerator.validateCode
property CodeNamespace.Types: CodeTypeDeclarationCollection
Multiple items
type CodeTypeDeclaration =
inherit CodeTypeMember
new : unit -> CodeTypeDeclaration + 1 overload
member BaseTypes : CodeTypeReferenceCollection
member IsClass : bool with get, set
member IsEnum : bool with get, set
member IsInterface : bool with get, set
member IsPartial : bool with get, set
member IsStruct : bool with get, set
member Members : CodeTypeMemberCollection
member TypeAttributes : TypeAttributes with get, set
member TypeParameters : CodeTypeParameterCollection
...
Full name: System.CodeDom.CodeTypeDeclaration
--------------------
CodeTypeDeclaration() : unit
CodeTypeDeclaration(name: string) : unit
module Seq
from Microsoft.FSharp.Collections
val iter : action:('T -> unit) -> source:seq<'T> -> unit
Full name: Microsoft.FSharp.Collections.Seq.iter
val t : CodeTypeDeclaration
val xmlType : CodeAttributeDeclaration option
property CodeTypeMember.CustomAttributes: CodeAttributeDeclarationCollection
Multiple items
type CodeAttributeDeclaration =
new : unit -> CodeAttributeDeclaration + 4 overloads
member Arguments : CodeAttributeArgumentCollection
member AttributeType : CodeTypeReference
member Name : string with get, set
Full name: System.CodeDom.CodeAttributeDeclaration
--------------------
CodeAttributeDeclaration() : unit
CodeAttributeDeclaration(name: string) : unit
CodeAttributeDeclaration(attributeType: CodeTypeReference) : unit
CodeAttributeDeclaration(name: string, [<System.ParamArray>] arguments: CodeAttributeArgument []) : unit
CodeAttributeDeclaration(attributeType: CodeTypeReference, [<System.ParamArray>] arguments: CodeAttributeArgument []) : unit
val tryFind : predicate:('T -> bool) -> source:seq<'T> -> 'T option
Full name: Microsoft.FSharp.Collections.Seq.tryFind
val a : CodeAttributeDeclaration
property CodeAttributeDeclaration.Name: string
System.Collections.CollectionBase.Clear() : unit
val iter : action:('T -> unit) -> option:'T option -> unit
Full name: Microsoft.FSharp.Core.Option.iter
CodeAttributeDeclarationCollection.Add(value: CodeAttributeDeclaration) : int
type CodeGenerator =
member GenerateCodeFromMember : member:CodeTypeMember * writer:TextWriter * options:CodeGeneratorOptions -> unit
static member IsValidLanguageIndependentIdentifier : value:string -> bool
static member ValidateIdentifiers : e:CodeObject -> unit
Full name: System.CodeDom.Compiler.CodeGenerator
CodeGenerator.ValidateIdentifiers(e: CodeObject) : unit
val saveToFile : outputFile:FileInfo -> codeNamespace:CodeNamespace -> unit
Full name: Script.XsdGenerator.saveToFile
val outputFile : FileInfo
val codeProvider : FSharpCodeProvider
Multiple items
type FSharpCodeProvider =
inherit CodeDomProvider
new : unit -> FSharpCodeProvider
Full name: FSharp.Compiler.CodeDom.FSharpCodeProvider
--------------------
new : unit -> FSharpCodeProvider
val writer : StreamWriter
Multiple items
type StreamWriter =
inherit TextWriter
new : stream:Stream -> StreamWriter + 6 overloads
member AutoFlush : bool with get, set
member BaseStream : Stream
member Close : unit -> unit
member Encoding : Encoding
member Flush : unit -> unit
member Write : value:char -> unit + 3 overloads
static val Null : StreamWriter
Full name: System.IO.StreamWriter
--------------------
StreamWriter(stream: Stream) : unit
StreamWriter(path: string) : unit
StreamWriter(stream: Stream, encoding: System.Text.Encoding) : unit
StreamWriter(path: string, append: bool) : unit
StreamWriter(stream: Stream, encoding: System.Text.Encoding, bufferSize: int) : unit
StreamWriter(path: string, append: bool, encoding: System.Text.Encoding) : unit
StreamWriter(path: string, append: bool, encoding: System.Text.Encoding, bufferSize: int) : unit
property FileSystemInfo.FullName: string
val options : CodeGeneratorOptions
Multiple items
type CodeGeneratorOptions =
new : unit -> CodeGeneratorOptions
member BlankLinesBetweenMembers : bool with get, set
member BracingStyle : string with get, set
member ElseOnClosing : bool with get, set
member IndentString : string with get, set
member Item : string -> obj with get, set
member VerbatimOrder : bool with get, set
Full name: System.CodeDom.Compiler.CodeGeneratorOptions
--------------------
CodeGeneratorOptions() : unit
CodeDomProvider.GenerateCodeFromNamespace(codeNamespace: CodeNamespace, writer: TextWriter, options: CodeGeneratorOptions) : unit
val generateClasses : namespace:string option -> outputFile:FileInfo -> xsdFile:FileInfo -> unit
Full name: Script.XsdGenerator.generateClasses
More information