【问题标题】:How to auto-generate code in specific .NET language based on an XSD/XML file如何基于 XSD/XML 文件以特定 .NET 语言自动生成代码
【发布时间】:2017-02-16 12:49:18
【问题描述】:

我需要将 XML 文件中的数据序列化为对象。这个对象类是在 XML 中定义的。有许多不同的 XML 文件,我想自动生成定义类的代码以节省时间并避免人为错误。自动生成的类可以是以下语言:VB、C#、JS、VJS、C++

如何实现从这个 XML 到特定语言的自动生成代码?

XML 文件的示例如下:

<?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>

***有很多包含更多内容的 XML 文件,我想从中自动生成代码,这个 XML 只是用来提供一个简单的示例。

【问题讨论】:

  • 你试过什么?任何代码示例? EnvDTE & VSIX 是您正在寻找的关键字。
  • @Tatranskymedved 我已经找到了解决方案,我只是想我会分享,将其发布为下面的答案
  • 我不喜欢你提出问题并立即给出答案的形式。这个论坛的方式应该是有人正在寻找问题的答案,而其他人正在解释解决方案(什么,为什么)。我接受你的回答很好,另一方面,这篇文章应该放在你的博客上,而不是利用问答论坛。
  • @Tatranskymedved 我发现查看其他人发布的问题以尝试为我自己找到答案非常有帮助,在这种情况下我找不到任何类似的问题,所以一旦我想出了一个解决方案我认为将其作为问题和答案发布对其他人会有所帮助,但我也一定会研究博客。
  • 我同意这一点,我也是这样做的,但是正如@DalmTo 所说,问题缺乏适当的形式化,老实说,我根本不理解这个话题。从 XML 文件在 .NET 中自动生成类?什么 XML 文件? XML 文件是否具有类结构或是否具有真实数据&您想重新创建它?一旦您以某人会寻找的方式指定它,一切都会变得更好。 =)

标签: c# c++ .net xml xsd.exe


【解决方案1】:

如果您想解析 XML 文件并在 .net 中创建一个自动生成的类,那么您应该使用 xsd.exe 工具来执行此操作,该工具是 Visual Studio 中开发工具的一部分。

您需要打开开发命令提示符才能运行该工具。 Open Command Prompt from inside Visual Studio

VS 2013 命令提示符的默认位置是here,但这可能会根据安装位置而改变。

在命令提示符中运行以下命令:

xsd '你的文件名'.xml

示例: 这将在目录文件夹中自动生成 XML 方案文件 'yourfilename'.xsd。

接下来,我们要使用自动创建的 XSD 文件以我们选择的语言自动生成代码:

xsd '你的文件名'.xsd /classes /language:vb

示例: 这将从 XSD 文件中创建一个自动生成的 .NET 类,该文件将包含在名为“yourfilename”.vb 的文件中。

然后您可以简单地将带有您的类的文件添加到您的项目中。

我选择 VB,但您可以选择:“CS”、“VB”、“JS”、“VJS”或“CPP”。

这是创建的 VB 文件中的代码:

'------------------------------------------------------------------------------
' <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

我再次运行 xsd.exe 工具也生成了 C# 类

以下是自动生成的代码:

    //------------------------------------------------------------------------------
    // <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;
        }
    }
}

**您也可以提供命名空间作为参数。

【讨论】:

  • 问题和答案都没有提供线索,最后会发生什么。问题是:问题太短、太宽泛且不清楚(您可以提供 xml 示例、结果类等以清楚地呈现 问题),答案看起来像是 2 个非常简单的步骤的组合(告诉我哪个更难):阅读有关 xsd 工具的文档并在 VS 中搜索如何做到这一点。
  • @Sinatr 我添加了一个 XML 示例以及该工具生成的文件内容。我希望这能让问题和答案更容易理解
猜你喜欢
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 2013-04-21
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多