-2

I need to serialize data from an XML file(s) to an object(s). This objects class is defined in the XML. There are many different XML files and I would like to auto-generate the code defining the class to save time and avoid making human mistake. Auto-generated class could be in these languages: VB, C#, JS, VJS, C++

How can I achieve auto-generating code from this XML into specific language?

An example of an XML File can be as follows:

<?xml version="1.0" encoding="utf-8" ?>
<MyFile VersionProduct="7.0" VersionCreate="7.00" VersionFile="7.00">
  <MyTable Size="20">
    <StandardTable Type="TXT">
      <MyRecord Priority="1"   Size="0" Length="350"   Weight="270"    Age="40" Ref="80"/>
      <MyRecord Priority="100" Size="0" Length="27080" Weight="27000"  Age="40" Ref="80"/>
    </StandardTable>
  </MyTable>
  <MyTable Size="28">
    <StandardTable Type="TXT">
      <MyRecord Priority="1"   Size="0" Length="350"   Weight="270"    Age="40" Ref="80"/>
      <MyRecord Priority="100" Size="0" Length="27080" Weight="27000"  Age="40" Ref="80"/>
    </StandardTable>
    <StandardTable Type="TRT">
      <MyRecord Priority="100" Size="0" Length="980"   Weight="900"    Age="40" Ref="0"/>
    </StandardTable>
  </MyTable>
</MyFile>

***There are many XML files with much more content which I would like to auto-generate code from, this XML was just used to provide a simple example.

Merav Kochavi
  • 4,223
  • 2
  • 32
  • 37
  • 1
    What have You tried? Any code example? `EnvDTE` & `VSIX` are keywords You are looking for. – Tatranskymedved Feb 16 '17 at 12:50
  • @Tatranskymedved I found the solution already, I just thought I would share, posted it as an answer below – Merav Kochavi Feb 16 '17 at 12:54
  • If you downvote, please explain, I would be happy to alter my question – Merav Kochavi Feb 16 '17 at 12:55
  • 1
    I dislike the form where You put question & immediately put answer. This forum should be in a way that somebody is looking for an answer to a question and somebody other is explaining the solution (what, why). I accept that Your answer is good, on the other hand this post should go on Your blog instead of utilizing Q&A forum. – Tatranskymedved Feb 16 '17 at 12:58
  • Posting a question followed by an answer is fine. Assuming that the question is in fact valid. The way your question is written it is to broad. – Linda Lawton - DaImTo Feb 16 '17 at 13:03
  • 1
    @Tatranskymedved I find it very helpful looking through questions others posted to try and find answers for my own, and in this case I could not find any similar questions, so once I did come up with a solution I thought it would be helpful for others to post it as a question and answer, but I will be sure to look into blogging as well. – Merav Kochavi Feb 16 '17 at 13:03
  • @DalmTo I agree with you, and that is why I immediately poster that I am happy to alter my question, I am open for suggestions on how to better phrase the question rather than unhelpful criticism. – Merav Kochavi Feb 16 '17 at 13:06
  • 2
    I agree on that, I do it the same way, however as @DalmTo said there is lack of proper formalization of question & honestly I would not understand the topic at all. auto-generate class in .NET from an XML file? What XML file? Is XML file having structure of class or does it have real data & You want to recreate it? Once You will specify this in a way that somebody will look for it, all will get much better. =) – Tatranskymedved Feb 16 '17 at 13:17

1 Answers1

1

If you want to parse an XML file and to create an auto-generated class in .net then you should do this using the xsd.exe tool which comes as part of the Dev tools in Visual Studio.

You will need to open the Dev Command Prompt to run the tool. Open Command Prompt from inside Visual Studio

The default location for Command Prompt for VS 2013 is here, but this could change according to installation location.

In the Command Prompt run the following commands:

xsd 'yourfilename'.xml

Example: enter image description here This will auto-generate the XML Scheme File 'yourfilename'.xsd in the directory folder.

Next, we want to auto-generate the code using the auto-created XSD file in the language of our choice:

xsd 'yourfilename'.xsd /classes /language:vb

Example: enter image description here This will create an auto-generate .NET class from the XSD file which will be contained in a file called 'yourfilename'.vb.

Then you can simply add the file with your class to your project.

I choose VB but you could select: 'CS', 'VB', 'JS', 'VJS' or 'CPP'.

This is the code in the VB file which was created:

'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'     Runtime Version:4.0.30319.42000
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict Off
Option Explicit On

Imports System.Xml.Serialization

'
'This source code was auto-generated by xsd, Version=4.0.30319.33440.
'

'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440"),  _
 System.SerializableAttribute(),  _
 System.Diagnostics.DebuggerStepThroughAttribute(),  _
 System.ComponentModel.DesignerCategoryAttribute("code"),  _
 System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true),  _
 System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=false)>  _
Partial Public Class MyFile

    Private myTableField() As MyFileMyTable

    Private versionProductField As String

    Private versionCreateField As String

    Private versionFileField As String

    '''<remarks/>
    <System.Xml.Serialization.XmlElementAttribute("MyTable", Form:=System.Xml.Schema.XmlSchemaForm.Unqualified)>  _
    Public Property MyTable() As MyFileMyTable()
        Get
            Return Me.myTableField
        End Get
        Set
            Me.myTableField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property VersionProduct() As String
        Get
            Return Me.versionProductField
        End Get
        Set
            Me.versionProductField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property VersionCreate() As String
        Get
            Return Me.versionCreateField
        End Get
        Set
            Me.versionCreateField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property VersionFile() As String
        Get
            Return Me.versionFileField
        End Get
        Set
            Me.versionFileField = value
        End Set
    End Property
End Class

'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440"),  _
 System.SerializableAttribute(),  _
 System.Diagnostics.DebuggerStepThroughAttribute(),  _
 System.ComponentModel.DesignerCategoryAttribute("code"),  _
 System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true)>  _
Partial Public Class MyFileMyTable

    Private standardTableField() As MyFileMyTableStandardTable

    Private sizeField As String

    '''<remarks/>
    <System.Xml.Serialization.XmlElementAttribute("StandardTable", Form:=System.Xml.Schema.XmlSchemaForm.Unqualified)>  _
    Public Property StandardTable() As MyFileMyTableStandardTable()
        Get
            Return Me.standardTableField
        End Get
        Set
            Me.standardTableField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Size() As String
        Get
            Return Me.sizeField
        End Get
        Set
            Me.sizeField = value
        End Set
    End Property
End Class

'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440"),  _
 System.SerializableAttribute(),  _
 System.Diagnostics.DebuggerStepThroughAttribute(),  _
 System.ComponentModel.DesignerCategoryAttribute("code"),  _
 System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true)>  _
Partial Public Class MyFileMyTableStandardTable

    Private myRecordField() As MyFileMyTableStandardTableMyRecord

    Private typeField As String

    '''<remarks/>
    <System.Xml.Serialization.XmlElementAttribute("MyRecord", Form:=System.Xml.Schema.XmlSchemaForm.Unqualified)>  _
    Public Property MyRecord() As MyFileMyTableStandardTableMyRecord()
        Get
            Return Me.myRecordField
        End Get
        Set
            Me.myRecordField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Type() As String
        Get
            Return Me.typeField
        End Get
        Set
            Me.typeField = value
        End Set
    End Property
End Class

'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440"),  _
 System.SerializableAttribute(),  _
 System.Diagnostics.DebuggerStepThroughAttribute(),  _
 System.ComponentModel.DesignerCategoryAttribute("code"),  _
 System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true)>  _
Partial Public Class MyFileMyTableStandardTableMyRecord

    Private priorityField As String

    Private sizeField As String

    Private lengthField As String

    Private weightField As String

    Private ageField As String

    Private refField As String

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Priority() As String
        Get
            Return Me.priorityField
        End Get
        Set
            Me.priorityField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Size() As String
        Get
            Return Me.sizeField
        End Get
        Set
            Me.sizeField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Length() As String
        Get
            Return Me.lengthField
        End Get
        Set
            Me.lengthField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Weight() As String
        Get
            Return Me.weightField
        End Get
        Set
            Me.weightField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Age() As String
        Get
            Return Me.ageField
        End Get
        Set
            Me.ageField = value
        End Set
    End Property

    '''<remarks/>
    <System.Xml.Serialization.XmlAttributeAttribute()>  _
    Public Property Ref() As String
        Get
            Return Me.refField
        End Get
        Set
            Me.refField = value
        End Set
    End Property
End Class

'''<remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440"),  _
 System.SerializableAttribute(),  _
 System.Diagnostics.DebuggerStepThroughAttribute(),  _
 System.ComponentModel.DesignerCategoryAttribute("code"),  _
 System.Xml.Serialization.XmlTypeAttribute(AnonymousType:=true),  _
 System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=false)>  _
Partial Public Class NewDataSet

    Private itemsField() As MyFile

    '''<remarks/>
    <System.Xml.Serialization.XmlElementAttribute("MyFile")>  _
    Public Property Items() As MyFile()
        Get
            Return Me.itemsField
        End Get
        Set
            Me.itemsField = value
        End Set
    End Property
End Class

I ran the xsd.exe tool again to generate C# class as well

enter image description here

and the following was the code which was auto-genearted:

    //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated by a tool.
    //     Runtime Version:4.0.30319.42000
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------

    using System.Xml.Serialization;

    // 
    // This source code was auto-generated by xsd, Version=4.0.30319.33440.
    // 


    /// <remarks/>

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
    public partial class MyFile {


    private MyFileMyTable[] myTableField;

    private string versionProductField;

    private string versionCreateField;

    private string versionFileField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("MyTable", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public MyFileMyTable[] MyTable {
        get {
            return this.myTableField;
        }
        set {
            this.myTableField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string VersionProduct {
        get {
            return this.versionProductField;
        }
        set {
            this.versionProductField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string VersionCreate {
        get {
            return this.versionCreateField;
        }
        set {
            this.versionCreateField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string VersionFile {
        get {
            return this.versionFileField;
        }
        set {
            this.versionFileField = value;
        }
    }


 }

    /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
    public partial class MyFileMyTable {

    private MyFileMyTableStandardTable[] standardTableField;

    private string sizeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("StandardTable", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public MyFileMyTableStandardTable[] StandardTable {
        get {
            return this.standardTableField;
        }
        set {
            this.standardTableField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Size {
        get {
            return this.sizeField;
        }
        set {
            this.sizeField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class MyFileMyTableStandardTable {

    private MyFileMyTableStandardTableMyRecord[] myRecordField;

    private string typeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("MyRecord", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public MyFileMyTableStandardTableMyRecord[] MyRecord {
        get {
            return this.myRecordField;
        }
        set {
            this.myRecordField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Type {
        get {
            return this.typeField;
        }
        set {
            this.typeField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class MyFileMyTableStandardTableMyRecord {

    private string priorityField;

    private string sizeField;

    private string lengthField;

    private string weightField;

    private string ageField;

    private string refField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Priority {
        get {
            return this.priorityField;
        }
        set {
            this.priorityField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Size {
        get {
            return this.sizeField;
        }
        set {
            this.sizeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Length {
        get {
            return this.lengthField;
        }
        set {
            this.lengthField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Weight {
        get {
            return this.weightField;
        }
        set {
            this.weightField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Age {
        get {
            return this.ageField;
        }
        set {
            this.ageField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Ref {
        get {
            return this.refField;
        }
        set {
            this.refField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSet {

    private MyFile[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("MyFile")]
    public MyFile[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

**You can also provide the namespace as a parameter.

Merav Kochavi
  • 4,223
  • 2
  • 32
  • 37
  • 3
    Neither question nor answer gives clues what will happens at the end. The problem is: question is too short, broad and unclear (you can provide xml example, resulting class, etc. to clearly present the *problem*), answer looks like a combination of 2 very simple steps (tell me which one is harder): reading documentation about xsd tool and googling for how to do it from within VS. – Sinatr Feb 16 '17 at 12:58
  • @Sinatr I added an XML example as well as the file content which the tool has produced. I hope this makes it easier to understand the question and answer – Merav Kochavi Feb 16 '17 at 13:36