项目作者: mganss

项目描述 :
Generate C# classes from XML Schema files
高级语言: C#
项目地址: git://github.com/mganss/XmlSchemaClassGenerator.git
创建时间: 2013-12-19T16:17:42Z
项目社区:https://github.com/mganss/XmlSchemaClassGenerator

开源协议:Apache License 2.0

下载


XmlSchemaClassGenerator

Nuget
Build status
codecov.io
netstandard2.0
net462

A console program and library to generate
XmlSerializer compatible C# classes
from XML Schema) files.

Features

  • Map XML namespaces to C# namespaces, either explicitly or through a (configurable) function
  • Generate C# XML comments from schema annotations
  • Generate DataAnnotations attributes
    from schema restrictions
  • Use Collection<T> properties
    (initialized in constructor and with private setter)
  • Map xs:integer and derived types to the closest possible .NET type, if not possible - fall back to string. Can be overriden by explicitly defined type (int, long, or decimal)
  • Automatic properties
  • Pascal case for classes and properties
  • Generate nullable adapter properties for optional elements and attributes without default values (see below)
  • Optional support for PCL
  • Optional support for INotifyPropertyChanged
  • Optional support for Entity Framework Code First (automatically generate key properties)
  • Optionally generate interfaces for groups and attribute groups
  • Optionally generate one file per class
  • Support for nullable reference types (NRTs) through AllowNullAttribute and MaybeNullAttribute
  • Optionally generate a common specific type for union member types

Unsupported:

  • Some restriction types
  • Recursive choices and choices whose elements have minOccurs > 0 or nillable=”true” (see below)
  • Possible name clashes and invalid identifiers when names contain non-alphanumeric characters
  • Groups with maxOccurs > 0

Usage

For command line use, choose your preferred installation:

  1. Usage: xscgen [OPTIONS]+ xsdFile...
  2. Generate C# classes from XML Schema files.
  3. Version ...
  4. xsdFiles may contain globs, e.g. "content\{schema,xsd}\**\*.xsd", and URLs.
  5. Append - to option to disable it, e.g. --interface-.
  6.  
  7. Options:
  8. -h, --help show this message and exit
  9. -n, --namespace=VALUE map an XML namespace to a C# namespace
  10. Separate XML namespace and C# namespace by '='.
  11. A single value (no '=') is taken as the C#
  12. namespace the empty XML namespace is mapped to.
  13. One option must be given for each namespace to
  14. be mapped.
  15. A file name may be given by appending a pipe
  16. sign (|) followed by a file name (like schema.
  17. xsd) to the XML namespace.
  18. If no mapping is found for an XML namespace, a
  19. name is generated automatically (may fail).
  20. --nf, --namespaceFile=VALUE
  21. file containing mappings from XML namespaces to C#
  22. namespaces
  23. The line format is one mapping per line: XML
  24. namespace = C# namespace [optional file name].
  25. Lines starting with # and empty lines are
  26. ignored.
  27. --tns, --typeNameSubstitute=VALUE
  28. substitute a generated type/member name
  29. Separate type/member name and substitute name by
  30. '='.
  31. Prefix type/member name with an appropriate kind
  32. ID as documented at: https://t.ly/HHEI.
  33. Prefix with 'A:' to substitute any type/member.
  34. --tnsf, --typeNameSubstituteFile=VALUE
  35. file containing generated type/member name
  36. substitute mappings
  37. The line format is one mapping per line:
  38. prefixed type/member name = substitute name.
  39. Lines starting with # and empty lines are
  40. ignored.
  41. -o, --output=FOLDER the FOLDER to write the resulting .cs files to
  42. -d, --datetime-offset map xs:datetime and derived types to System.
  43. DateTimeOffset instead of System.DateTime
  44. -i, --integer=TYPE map xs:integer and derived types to TYPE instead
  45. of automatic approximation
  46. TYPE can be i[nt], l[ong], or d[ecimal]
  47. --fb, --fallback, --use-integer-type-as-fallback
  48. use integer type specified via -i only if no type
  49. can be deduced
  50. -e, --edb, --enable-data-binding
  51. enable INotifyPropertyChanged data binding
  52. -r, --order emit order for all class members stored as XML
  53. element
  54. -c, --pcl PCL compatible output
  55. -p, --prefix=PREFIX the PREFIX to prepend to auto-generated namespace
  56. names
  57. -v, --verbose print generated file names on stdout
  58. -0, --nullable generate nullable adapter properties for optional
  59. elements/attributes w/o default values
  60. -f, --ef generate Entity Framework Code First compatible
  61. classes
  62. -t, --interface generate interfaces for groups and attribute
  63. groups (default is enabled)
  64. -a, --pascal use Pascal case for class and property names (
  65. default is enabled)
  66. --av, --assemblyVisible
  67. use the internal visibility modifier (default is
  68. false)
  69. -u, --enableUpaCheck should XmlSchemaSet check for Unique Particle
  70. Attribution (UPA) (default is enabled)
  71. --ct, --collectionType=VALUE
  72. collection type to use (default is System.
  73. Collections.ObjectModel.Collection`1)
  74. --cit, --collectionImplementationType=VALUE
  75. the default collection type implementation to use (
  76. default is null)
  77. --csm, --collectionSettersMode=Private, Public, PublicWithoutConstructorInitialization, Init, InitWithoutConstructorInitialization
  78. generate a private, public, or init-only setter
  79. with or without backing field initialization for
  80. collections
  81. (default is Private; can be: Private, Public,
  82. PublicWithoutConstructorInitialization, Init,
  83. InitWithoutConstructorInitialization)
  84. --ctro, --codeTypeReferenceOptions=GlobalReference, GenericTypeParameter
  85. the default CodeTypeReferenceOptions Flags to use (
  86. default is unset; can be: GlobalReference,
  87. GenericTypeParameter)
  88. --tvpn, --textValuePropertyName=VALUE
  89. the name of the property that holds the text value
  90. of an element (default is Value)
  91. --dst, --debuggerStepThrough
  92. generate DebuggerStepThroughAttribute (default is
  93. enabled)
  94. --dc, --disableComments
  95. do not include comments from xsd
  96. --nu, --noUnderscore do not generate underscore in private member name (
  97. default is false)
  98. --da, --description generate DescriptionAttribute (default is true)
  99. --cc, --complexTypesForCollections
  100. generate complex types for collections (default is
  101. true)
  102. -s, --useShouldSerialize use ShouldSerialize pattern instead of Specified
  103. pattern (default is false)
  104. --sf, --separateFiles generate a separate file for each class (default
  105. is false)
  106. --nh, --namespaceHierarchy
  107. generate a separate folder for namespace hierarchy.
  108. Implies "separateFiles" if true (default is
  109. false)
  110. --sg, --separateSubstitutes
  111. generate a separate property for each element of a
  112. substitution group (default is false)
  113. --dnfin, --doNotForceIsNullable
  114. do not force generator to emit IsNullable = true
  115. in XmlElement annotation for nillable elements
  116. when element is nullable (minOccurs < 1 or
  117. parent element is choice) (default is false)
  118. --cn, --compactTypeNames
  119. use type names without namespace qualifier for
  120. types in the using list (default is false)
  121. --cl, --commentLanguages=VALUE
  122. comment languages to use (default is en; supported
  123. are en, de)
  124. --un, --uniqueTypeNames
  125. generate type names that are unique across
  126. namespaces (default is false)
  127. --gc, --generatedCodeAttribute
  128. add version information to GeneratedCodeAttribute (
  129. default is true)
  130. --nc, --netCore generate .NET Core specific code that might not
  131. work with .NET Framework (default is false)
  132. --nr, --nullableReferenceAttributes
  133. generate attributes for nullable reference types (
  134. default is false)
  135. --ar, --useArrayItemAttribute
  136. use ArrayItemAttribute for sequences with single
  137. elements (default is true)
  138. --es, --enumAsString Use string instead of enum for enumeration
  139. --ca, --commandArgs generate a comment with the exact command line
  140. arguments that were used to generate the source
  141. code (default is true)
  142. --uc, --unionCommonType
  143. generate a common type for unions if possible (
  144. default is false)
  145. --dtd, --allowDtdParse
  146. allow DTD parsing (default is false)
  147. --ns, --namingScheme use the specified naming scheme for class and
  148. property names (default is Pascal; can be:
  149. Direct, Pascal, Legacy)
  150. --fu, --forceUriScheme=VALUE
  151. force URI scheme when resolving URLs (default is
  152. none; can be: none, same, or any defined value
  153. for scheme, like https or http)

For use from code use the library NuGet package:

  1. var generator = new Generator
  2. {
  3. OutputFolder = outputFolder,
  4. Log = s => Console.Out.WriteLine(s),
  5. GenerateNullables = true,
  6. NamespaceProvider = new Dictionary<NamespaceKey, string>
  7. {
  8. { new NamespaceKey("http://wadl.dev.java.net/2009/02"), "Wadl" }
  9. }
  10. .ToNamespaceProvider(new GeneratorConfiguration { NamespacePrefix = "Wadl" }.NamespaceProvider.GenerateNamespace)
  11. };
  12. generator.Generate(files);

Specifying the NamespaceProvider is optional. If you don’t provide one, C# namespaces will be generated automatically. The example above shows how to create a custom NamespaceProvider that has a dictionary for a number of specific namespaces as well as a generator function for XML namespaces that are not in the dictionary. In the example the generator function is the default function but with a custom namespace prefix. You can also use a custom generator function, e.g.

  1. var generator = new Generator
  2. {
  3. NamespaceProvider = new NamespaceProvider
  4. {
  5. GenerateNamespace = key => ...
  6. }
  7. };

Mapping xsd files to C# namespaces

Using the optional | syntax of the -n command line option you can map individual xsd files to C# namespaces. If you have several input files using the same XML namespace you can still generate an individual C# namespace for the types defined within a single xsd file. For example, if you have two input files a.xsd and b.xsd both of which have the same targetNamespace of http://example.com/namespace you can generate the C# namespaces Example.NamespaceA and Example.NamespaceB:

  1. xscgen -n "|a.xsd=Example.NamespaceA" -n "|b.xsd=Example.NamespaceB" a.xsd b.xsd

Mapping empty XML namespaces

In order to provide a C# namespace name for an empty XML namespace you can specify it on the command line like this:

  1. xscgen -n Example example.xsd

An alternative form that is also valid is -n =Example. Note the space between -n and =Example.

Using mapping files

Instead of specifying the namespace mappings on the command line you can also use a mapping file which should contain one mapping per line in the following format:

  1. # Comment
  2. http://example.com = Example.NamespaceA a.xsd
  3. http://example.com = Example.NamespaceB b.xsd
  4. Empty
  5. # or alternatively
  6. = Empty

Use the --nf option to specify the mapping file.

Substituting generated C# type and member names

If a xsd file specifies obscure names for their types (classes, enums) or members (properties), you can substitute these using the --tns/--typeNameSubstitute= parameter:

  1. xscgen --tns T:Example_RootType=Example --tns T:Example_RootTypeExampleScope=ExampleScope --tns P:StartDateDateTimeValue=StartDate example.xsd

The syntax for substitution is: {kindId}:{generatedName}={substituteName}

The {kindId} is a single character identifier based on documentation/analysis ID format, where valid values are:

ID Scope
P Property
T Type: class, enum, interface
A Any property and/or type

Using substitution files

Instead of specifying the substitutions on the command line you can also use a substitution file which should contain one substitution per line in the following format:

  1. # Comment
  2. T:Example_RootType = Example
  3. T:Example_RootTypeExampleScope = ExampleScope
  4. P:StartDateDateTimeValue = StartDate

Use the --tnsf/--typeNameSubstituteFile option to specify the substitution file.

" class="reference-link">Nullables

XmlSerializer has been present in the .NET Framework since version 1.1
and has never been updated to provide support for nullables
which are a natural fit for the problem of signaling the absence or presence of a value type
but have only been present since .NET Framework 2.0.

Instead XmlSerializer has support for a pattern where you provide an additional bool property
with “Specified” appended to the name to signal if the original property should be serialized.
For example:

  1. <xs:attribute name="id" type="xs:int" use="optional">...</xs:attribute>
  1. [System.Xml.Serialization.XmlAttributeAttribute("id", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="int")]
  2. public int Id { get; set; }
  3. [System.Xml.Serialization.XmlIgnoreAttribute()]
  4. public bool IdSpecified { get; set; }

XmlSchemaClassGenerator can optionally generate an additional nullable property that works as an adapter to both properties:

  1. [System.Xml.Serialization.XmlAttributeAttribute("id", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="int")]
  2. public int IdValue { get; set; }
  3. [System.Xml.Serialization.XmlIgnoreAttribute()]
  4. public bool IdValueSpecified { get; set; }
  5. [System.Xml.Serialization.XmlIgnoreAttribute()]
  6. public System.Nullable<int> Id
  7. {
  8. get
  9. {
  10. if (this.IdValueSpecified)
  11. {
  12. return this.IdValue;
  13. }
  14. else
  15. {
  16. return null;
  17. }
  18. }
  19. set
  20. {
  21. this.IdValue = value.GetValueOrDefault();
  22. this.IdValueSpecified = value.HasValue;
  23. }
  24. }

" class="reference-link">Choice Elements

The support for choice elements differs from that provided by xsd.exe.
Xsd.exe generates a property called Item of type object and, if not all choices have a distinct type,
another enum property that selects the chosen element.
Besides being non-typesafe and non-intuitive, this approach breaks apart if the choices have a more complicated structure (e.g. sequences),
resulting in possibly schema-invalid XML.

XmlSchemaClassGenerator currently simply pretends choices are sequences.
This means you’ll have to take care only to set a schema-valid combination of these properties to non-null values.

" class="reference-link">Interfaces

Groups and attribute groups in XML Schema are reusable components that can be included in multiple type definitions. XmlSchemaClassGenerator can optionally generate interfaces from these groups to make it easier to access common properties on otherwise unrelated classes. So

  1. <xs:attributeGroup name="Common">
  2. <xs:attribute name="name" type="xs:string"></xs:attribute>
  3. </xs:attributeGroup>
  4. <xs:complexType name="A">
  5. <xs:attributeGroup ref="Common"></xs:attributeGroup>
  6. </xs:complexType>
  7. <xs:complexType name="B">
  8. <xs:attributeGroup ref="Common"></xs:attributeGroup>
  9. </xs:complexType>

becomes

  1. public partial interface ICommon
  2. {
  3. string Name { get; set; }
  4. }
  5. public partial class A: ICommon
  6. {
  7. public string Name { get; set; }
  8. }
  9. public partial class B: ICommon
  10. {
  11. public string Name { get; set; }
  12. }

Collection types

Values for the --collectionType and --collectionImplementationType options have to be given in the format accepted by
the Type.GetType() method. For the System.Collections.Generic.List<T> class this means System.Collections.Generic.List`1.
Make sure to escape the backtick character (` ) to prevent it from being interpreted by the shell.

Integer and derived types

Not all numeric types defined by XML Schema can be safely and accurately mapped to .NET numeric data types, however, it’s possible to approximate the mapping based on the integer bounds and restrictions such as totalDigits.
If an explicit integer type mapping is specified via --integer=TYPE, that type will be used, otherwise an approximation will be made based on the table below. If you additionally specify --fallback, the type specified via --integer=TYPE will be used only if no type can be deduced by applying the rules below.

If the restrictions minInclusive and maxInclusive are present on the integer element, then the smallest CLR type that fully encompasses the specified range will be used. Unsigned types are given precedence over signed types. The following table shows the possible ranges and their corresponding CLR type, in the order they will be applied.
















Minimum (Inclusive) Maximum (Inclusive) C# type
sbyte.MinValuesbyte.MaxValuesbyte
byte.MinValuebyte.MaxValuebyte
ushort.MinValueushort.MaxValueushort
short.MinValueshort.MaxValueshort
uint.MinValueuint.MaxValueuint
int.MinValueint.MaxValueint
ulong.MinValueulong.MaxValueulong
long.MinValuelong.MaxValuelong
decimal.MinValuedecimal.MaxValuedecimal

If the range specified by minInclusive and maxInclusive does not fit in any CLR type, or if those restrictions are not present, then the totalDigits restriction will be used, as shown in the following table.



















XML Schema type totalDigits C# type
xs:positiveInteger
xs:nonNegativeInteger
<3byte
<5ushort
<10uint
<20ulong
<30decimal
>=30string
xs:integer
xs:nonPositiveInteger
xs:negativeInteger
<3sbyte
<5short
<10int
<19long
<29decimal
>=29string

Unions

If you specify --unionCommonType, XmlSchemaClassGenerator will try to determine a common type for a union’s member types. If, for example, the member types
are all integer types, then the narrowest integer type will be used that can fit all member types.

Note that semantic issues might arise with this approach. For example, DateTime values are serialized with both date and time information included. See discussion at #397.

Contributing

Contributions are welcome. Here are some guidelines:

  • If it’s not a trivial fix, please submit an issue first
  • Try and blend new code with the existing code’s style
  • Add unit tests