Nick
Nick

Reputation: 123

How to programmatically convert schema to C# class in .NET core

I'm looking for a way to convert schema to C# class in .NET core. In .NET framework, i was using class XmlCodeExporter to achieve this but seems this has not been ported to .NET For example, here is a simple shema:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:complexType name="sometype">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="somestring" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
  <xs:element name="sometype" nillable="true" type="sometype" />
</xs:schema>

I can run xsd tool to generate following class: xsd.exe Schema.xsd /c

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=true)]
public partial class sometype {
    
    private string somestringField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string somestring {
        get {
            return this.somestringField;
        }
        set {
            this.somestringField = value;
        }
    }
}

How can i achieve this programmatically?

Thanks in advance for any help provided

Upvotes: 0

Views: 600

Answers (1)

mamift
mamift

Reputation: 927

Microsoft in the past had a tool called LinqToXsd that is essentially a better version of XSD.exe.

While they don't support it themselves anymore, it has been ported to .NET core by the community as LinqToXsdCore. It's on GitHub: https://github.com/mamift/LinqToXsdCore

It runs on .NET Core, but the code it generates targets .NET Standard 2.0 so you can use its code to target .NET Framework/.NET Core.

Edit: It has code generation facillities that are accessible programmatically if you check https://github.com/mamift/LinqToXsdCore/blob/master/XObjectsCode/Src/XObjectsCoreGenerator.cs

Upvotes: 1

Related Questions