.net 从 XSD 生成 DataContract

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2188909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:51:57  来源:igfitidea点击:

Generate DataContract from XSD

.netwcfxsddatacontract

提问by Daveo

I want to be able to generate a DataContractfrom a XSD file, preferably using the xsd.exe tool. What is the easiest way for it to auto generate the [DataContract]and [DataMember]on each of my items?

我希望能够DataContract从 XSD 文件生成一个,最好使用xsd.exe 工具。它在我的每个项目上自动生成[DataContract]和的最简单方法是什么[DataMember]

Or is there a better approach? I am trying to avoid having to recreate the data contract each time the XSD file is changed and regenerated.

或者有更好的方法吗?我试图避免每次更改和重新生成 XSD 文件时都必须重新创建数据协定。

回答by marc_s

The xsd.exetool predates WCF and doesn't know anything about [DataContract]and [DataMember]. If you do use xsd.exe, you'll have to switch WCF to use the XmlSerializerinstead of its default DataContractSerializerfor serializing the data contracts.

xsd.exe工具早于 WCF 并且对[DataContract]and一无所知[DataMember]。如果确实使用xsd.exe,则必须切换 WCF 以使用XmlSerializer而不是其默认值DataContractSerializer来序列化数据协定。

The WCF equivalent for xsd.exeis svcutil.exe- it has a parameter /dconlywhich creates the data contracts only, from a given XSD file. This will generate a C# or VB.NET file for you, containing the data contracts nicely annotated.

WCF 等效于xsd.exeis svcutil.exe- 它有一个参数/dconly,它仅从给定的 XSD 文件创建数据协定。这将为您生成一个 C# 或 VB.NET 文件,其中包含很好地注释的数据协定。

Usage:

用法:

svcutil.exe (name of your XSD).xsd /dconly

This would generate a *.cs file by the same base name in your directory.

这将在您的目录中生成一个具有相同基本名称的 *.cs 文件。

In my experience, svcutil.exeis quite picky about its XML structures - so don't be surprised if it barks at you with tons of warnings and/or errors.

根据我的经验,svcutil.exe它对 XML 结构非常挑剔 - 所以如果它用大量警告和/或错误向您咆哮,请不要感到惊讶。

回答by zahirhas

Use svcutil.exe instead of xsd.exe

使用 svcutil.exe 而不是 xsd.exe

How to Use ? Go to Start Menu --> Microsoft Visual Studio 2008 --> Visual Studio Tools --> Visual Studio 2008 Command Prompt

如何使用 ?转到开始菜单 --> Microsoft Visual Studio 2008 --> Visual Studio 工具 --> Visual Studio 2008 命令提示符

and Change the directoy you want or change the directory to whre your xsd is there.

并更改您想要的目录或将目录更改为您的 xsd 所在的位置。

svcutil.exe /help 

it will list all the options.

它将列出所有选项。

one of the option I use to generate data contarct only is

我用来生成数据合同的选项之一是

svcutil.exe /target:code /n:*,[Your Company and Department].Common.DataTransferObjects /dataContractOnly /serializer:auto /importXmlTypes common.xsd /out:common.cs

Keep coding hava good day!

继续编码祝你有美好的一天!

回答by pavelz

DataContracts from XSD first!

首先是来自 XSD 的 DataContracts!

It is the modern way and very good practice, however, VS2010 has very limited automation support for it. Hence, I sat down and wrote a pure msbuild target which: does not require proj file modifications and generates .g.cs. You can also achieve generating VB code very easily with small tweaks in this file.

这是现代方法和非常好的实践,但是,VS2010 对它的自动化支持非常有限。因此,我坐下来编写了一个纯 msbuild 目标,它不需要修改 proj 文件并生成 .g.cs。您还可以通过在此文件中进行一些小的调整来非常轻松地生成 VB 代码。

Instalaltion: Copy the code and save it as GenerateDataContractsFromXSD.targets file into the folder 'C:\Program Files\MSBuild\4.0\Microsoft.Common.targets\ImportAfter'. This makes msbuild to read it each time it starts and same applies for VS2010.

安装:复制代码并将其作为 GenerateDataContractsFromXSD.targets 文件保存到文件夹“C:\Program Files\MSBuild\4.0\Microsoft.Common.targets\ImportAfter”中。这使得 msbuild 每次启动时都会读取它,这同样适用于 VS2010。

Usage:

用法:

  • ReStart VS2010 and add an xsd into your project.
  • Select the XSD file and press F4 in order to display properties tool window.
  • Change the Build Action property to contain value GenerateDataContracts
  • Build the project with the XSD file. It generates the first .g.cs file.
  • Chnage the view in the Solution Explorer to show all files on the file system.
  • Include the new generated file in the project.
  • Add reference to System.Runtime.Serialization assembly.
  • 重新启动 VS2010 并将 xsd 添加到您的项目中。
  • 选择 XSD 文件并按 F4 以显示属性工具窗口。
  • 将 Build Action 属性更改为包含值 GenerateDataContracts
  • 使用 XSD 文件构建项目。它生成第一个 .g.cs 文件。
  • 更改解决方案资源管理器中的视图以显示文件系统上的所有文件。
  • 在项目中包含新生成的文件。
  • 添加对 System.Runtime.Serialization 程序集的引用。

Enjoy.

享受。

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- Inject into the sequence of targets in order to add a generated file to compile -->
  <PropertyGroup>
    <CoreCompileDependsOn>
      GenerateDataContractsFromXSD;
      $(CoreCompileDependsOn);
    </CoreCompileDependsOn>
  </PropertyGroup>

  <ItemGroup>
    <SvcUtilParam Include="/nologo" />
    <SvcUtilParam Include="/target:code" />
    <SvcUtilParam Include="/dataContractOnly" />
    <SvcUtilParam Include="/serializer:DataContractSerializer" />
    <SvcUtilParam Include="/language:csharp" />
    <SvcUtilParam Include="/enableDataBinding" />
    <SvcUtilParam Include="/serializable" />
    <SvcUtilParam Include="/internal" />
  </ItemGroup>

  <ItemGroup>
    <AvailableItemName Include="GenerateDataContracts">
      <Targets>GenerateDataContractsFromXSD</Targets>
    </AvailableItemName>
  </ItemGroup>

  <ItemDefinitionGroup>
    <GenerateDataContracts>
      <!-- Use the following options to pass serialization options to SVCUTIL -->
      <DataContractSchemaMapping>"/n:*,$(AssemblyName).Data"</DataContractSchemaMapping>
    </GenerateDataContracts>
  </ItemDefinitionGroup>

  <!-- Automated Data Contract Serialisation using the SvcUtil.Exe tool -->
  <!-- in order to make it automated you have to set the build tool in properties window to GenerateDataContracts -->
  <Target Name="GenerateDataContractsFromXSD"
          Inputs="@(GenerateDataContracts)"
          Outputs="%(GenerateDataContracts.RootDir)\%(GenerateDataContracts.Directory)%(GenerateDataContracts.Filename).g.cs">

    <ItemGroup>
      <DataContractItems Include="@(GenerateDataContracts -> '%(FullPath)')" Condition="'%(Extension)' == '.xsd'" />
    </ItemGroup>

    <PropertyGroup>
      <DataContractGeneratedFilePath>%(DataContractItems.RootDir)\%(DataContractItems.Directory)%(DataContractItems.Filename).g.cs</DataContractGeneratedFilePath>
      <DataContractGeneratedIdentifier>@(GenerateDataContracts -> '%(RelativeDir)')%(DataContractItems.Filename).g.cs</DataContractGeneratedIdentifier>
    </PropertyGroup>

    <GetFrameworkSdkPath>
        <Output TaskParameter="Path" PropertyName="WIN_SDK_PATH" />
    </GetFrameworkSdkPath>

    <Exec 
      Condition="'@(DataContractItems)' != ''"
      Command="attrib -r &quot;$(DataContractGeneratedFilePath)&quot;" />

    <Exec
      Condition="'@(DataContractItems)' != ''"
      Outputs="$(DataContractGeneratedFilePath)"
      Command="&quot;$(WIN_SDK_PATH)bin\SvcUtil.exe&quot; @(SvcUtilParam, ' ') @(GenerateDataContracts -> '%(DataContractSchemaMapping)') &quot;/out:$(DataContractGeneratedFilePath)&quot; &quot;%(DataContractItems.FullPath)&quot;" />

  </Target>

  <Target Name="GetCopyGenerateDataContractItems"
          AfterTargets="AssignTargetPaths">
    <ItemGroup>
      <DataContractItems Include="@(GenerateDataContracts -> '%(FullPath)')" Condition="'%(Extension)' == '.xsd'" />
    </ItemGroup>

    <AssignTargetPath Files="@(DataContractItems)" RootFolder="$(MSBuildProjectDirectory)">
      <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath" />
    </AssignTargetPath>

  </Target>

 </Project>

回答by Jacques Mostert

On a 64-bit machine you will find it in

在 64 位机器上,您可以在

%systemdrive%\Program Files (x86)\MSBuild\<version you use>

In this case:

在这种情况下:

%systemdrive%\Program Files (x86)\MSBuild.0\Microsoft.Common.Targets\ImportAfter\