I'm trying to generate an xs:schema from any .net Type programmatically. I know I could use reflection and generate it by iterating over the public properties, but is there a built in way?
Example:
[Serializable]
public class Person
{
[XmlElement(IsNullable = false)] public string FirstName { get; set; }
[XmlElement(IsNullable = false)] public string LastName { get; set; }
[XmlElement(IsNullable = true)] public string PhoneNo { get; set; }
}
Desired Output:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Person" type="Person" />
<xs:complexType name="Person">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" form="unqualified" name="FirstName" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" form="unqualified" name="LastName" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" form="unqualified" name="PhoneNo" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
A data type within an XML document is a type that has been assigned to an element on the instance using the dt:dt attribute, or through an XML Schema, a formal definition of an XML document. In addition, data types can be declared as elements.
I found the accepted answer generated an incorrect schema given some of my attributes. e.g. It ignored custom names for enum values marked with [XmlEnum(Name="Foo")]
I believe this is the correct way (given your using XmlSerializer
) and is quite simple too:
var schemas = new XmlSchemas();
var exporter = new XmlSchemaExporter(schemas);
var mapping = new XmlReflectionImporter().ImportTypeMapping(typeof(Person));
exporter.ExportTypeMapping(mapping);
var schemaWriter = new StringWriter();
foreach (XmlSchema schema in schemas)
{
schema.Write(schemaWriter);
}
return schemaWriter.ToString();
Code extracted from: http://blogs.msdn.com/b/youssefm/archive/2010/05/13/using-xml-schema-import-and-export-for-xmlserializer.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With