问题
Put it simply, when I use XSD.exe (that comes with Visual Studio 2012) to generate XML schema file from this class:
[Serializable]
public class Person
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public int Age { get; set; }
}
I get this as the result:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person" nillable="true" type="Person" />
<xs:complexType name="Person">
<xs:attribute name="Name" type="xs:string" />
<xs:attribute name="Age" type="xs:int" use="required" />
</xs:complexType>
</xs:schema>
Notice that Age attribute is specified as required (it has use="required") in generated schema while attribute Name is not.
I use XSD.exe like this:
xsd.exe Sample.exe /type:Person
Where Sample.exe is .NET assembly where Person class is defined.
I would like to somehow specify in my class which XmlAttribute properties are required and which are not so that XSD.exe can automatically generate schema from that. Is this possible?
回答1:
Unless there's a bug in XSD (it is not clear if you tried what it is described in the XSD.exe documentation, specifically the attribute element binding support - right now I can't test it), the answer is yes, you can.
In your case, the different behaviour between Name and Age is simply due to the fact that a String field is nullable, whereas the int one is not (somehow I don't believe an int?
will make a difference in your case, still you can try it...) Attributes are not nillable (from an XSD perspective), therefore the use of optional.
Use Attribute: Generating an XML Schema document from classes
In either of the following two cases, Xsd.exe does not specify the use attribute, reverting to the default value optional:
• An extra public bool field that follows the Specified naming convention is present.
• A default value is assigned to the member via an attribute of type System.Component.DefaultValueAttribute.
If neither of these conditions is met, Xsd.exe produces a value of required for the use attribute.
来源:https://stackoverflow.com/questions/20958062/how-to-generate-xml-schema-from-c-sharp-type-with-xsd-exe-such-that-xmlattribut