Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...