Programmatically serialize class to xsd

扶醉桌前 提交于 2020-01-02 03:29:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!