问题
Is there a way to create an XSD from a C# .NET class programmatically? I want to serialize objects to xsd (or xml) with type information.
回答1:
Yes; look at XsdDataContractExporter
; MSDN has a full example here.
Alternative; XmlSchemaExporter
回答2:
This should give you the types as well! (if you are looking for xml solution, for xsd solution, Marc has the answer ;-))
var oEmp = new Emp { FirstName = "John", LastName = "Smith", DOJ = DateTime.Today };
using (var stream = File.Create("J:\\XML\\Employee.xml"))
{
var sri = new SoapReflectionImporter();
var xtm = sri.ImportTypeMapping(typeof(Emp));
var serializer = new XmlSerializer(xtm);
serializer.Serialize(stream, oEmp);
}
The output XML...
<?xml version="1.0"?>
<Emp xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<FirstName xsi:type="xsd:string">John</FirstName>
<LastName xsi:type="xsd:string">Smith</LastName>
<DOJ xsi:type="xsd:dateTime">2011-11-29T00:00:00+01:00</DOJ>
</Emp>
来源:https://stackoverflow.com/questions/8308500/programmatically-serialize-class-to-xsd