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.
Yes; look at XsdDataContractExporter
; MSDN has a full example here.
Alternative; XmlSchemaExporter
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>
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