Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically serialize class to xsd

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.

like image 279
Pking Avatar asked Nov 29 '11 09:11

Pking


2 Answers

Yes; look at XsdDataContractExporter; MSDN has a full example here.

Alternative; XmlSchemaExporter

like image 113
Marc Gravell Avatar answered Sep 20 '22 05:09

Marc Gravell


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>
like image 31
Numan Avatar answered Sep 20 '22 05:09

Numan