Reputation: 1602
I'm using Microsoft's excellent XSD.exe tool to build a C# object model from my XSD schema.
I would like to add additional C# attributes to the resulting C# file auto-generated by XSD object model (to define Validation behavior for Razor but maybe for other things too).
For example, in my XSD I have something like the following:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyThing">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="SomeThings">
<xs:complexType>
<xs:attribute name="Email" type="xs:string" use="required" />
The XSD tool will output a C# class with (amongst other things) a property such as this:
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
I am wondering what might be the best way to add additional C# property attributes such as
[Required]
[EmailAddress]
So the final C# would be:
/// <remarks/>
[Required]
[EmailAddress]
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
Can this be done with the XSD.exe tool (I couldn't find a way)? Or is there a way to add property attributes at runtime (is that a good idea)?
The ideal would be able to add this info the XSD, e.g.
<xs:attribute name="Email" someUnknownNamespace:customCSharpAttributes="Required,EmailAddress" type="xs:string" use="required" />
Upvotes: 0
Views: 320
Reputation: 153
This cannot be done with the XSD.exe tool - ostensibly, it has no idea what an EmailAddress
is, given that the field is given the type of xs:string
.
However, you mention Razor and this makes me think of the System.ComponentModel.DataAnnotations namespace. It has the given [Required]
attribute and a lot more, including one that does email address annotations.
As far as automatically annotating the data - the XML schema you provided is insufficient to automatically be annotated with the tools in that namespace.
There are open source solutions which do what you describe (given an adequate schema).
Upvotes: 1