Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically generate an xml schema from a type?

Tags:

c#

.net

xml

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>
like image 915
Zachary Yates Avatar asked Sep 09 '10 20:09

Zachary Yates


People also ask

Can we define a data type for an element in XML 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.


1 Answers

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

like image 166
Tyson Avatar answered Oct 13 '22 01:10

Tyson