简体   繁体   中英

How to generate XML Schema from C# type with XSD.exe such that [XmlAttribute] property is mapped to required XML attribute?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM