How to tell xsd.exe to use a specific .NET type for a custom xs:simpleType?

207 Views Asked by At

In my XSD I have some type definitions like this:

<xs:simpleType name="Ref_System">
    <xs:restriction base="xs:string">
        <xs:pattern value="[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"/>
    </xs:restriction>
</xs:simpleType>

Obviously, this defines a UUID. However, since the xs:simpleType is based on xs:string, the xsd.exe tool will create a string property for elements using this type Ref_System.

The following xs:complexType...

<xs:complexType name="Incident">
    <xs:sequence>
        <xs:element name="system" type="Ref_System" minOccurs="1" maxOccurs="1" />
        <!-- ... -->
    </xs:sequence>
</xs:complexType>

...will result in the following C# class:

public partial class Incident {
    private string systemField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)]
    public string system {
        get {
            return this.systemField;
        }
        set {
            this.systemField = value;
        }
    }

    // ...
}

Is there any way to tell the xsd.exe tool to generate Guid properties for elements which use the Ref_System type?

Note: It is not an option to change the XSD file since this is coming from an external source!

Note 2: I know that I can extend the partial class, define a custom Guid property in there and then convert the string property to the Guid property using XmlConvert.ToGuid(...). However, since I have lots of cases like this, I would like to avoid the manual work and use an automated approach instead.

1

There are 1 best solutions below

0
gehho On

If anyone is interested in a solution: I didn't find any way to tell xsd.exe to use another type in scenarios like this. Generally, xsd.exe seems to be very inflexible. That's why I looked for other tools and found the XmlSchemaClassGenerator project. This offers great flexibility, supports Nullable natively, supports separate files per class (using Generator.SeparateClasses), has lots of other nice features and provides quite some extension points. Furthermore, it is open source, so that you can adjust it to your needs if the available options are not sufficient.

In my case, I created a simple Console application and consumed the library NuGet package. See the "Usage" section of the project's Readme for details (scroll down to the paragraph starting with "For use from code...").

I used the Generator.MemberVisitor or Generator.TypeVisitor to make the generator use System.Guid for properties of type Ref_System. Unfortunately, I can't provide details or code since I changed to another company in the meantime, but it was not that complicated.