ChatGPT解决这个技术问题 Extra ChatGPT

How to generate .NET 4.0 classes from xsd?

What are the options to generate .NET 4.0 c# classes (entities) from an xsd file, using Visual Studio 2010?

@drzaus I had this work in the past, but now when I add one it generates as a DataSet class instead of the classes I would expect. I just add an existing item and select the XSD file.

M
Marc Gravell

simple enough; just run (at the vs command prompt)

xsd your.xsd /classes

(which will create your.cs). Note, however, that most of the intrinsic options here haven't changed much since 2.0

For the options, use xsd /? or see MSDN; for example /enableDataBinding can be useful.


"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\xsd.exe" /classes /language:CS your.xsd
Gravell to the rescue again! Though this answer is 100% right, in my case I found it easiest to add the xsd.exe directory path to the PATH environment variable. My computer -> properties -> advanced -> environment variables -> Path -- and add "C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\" (of course pay close attention to both the windows and .NET versions specific to your machine) -- happy coding!
For the case you have several interlinked schema definitions just name them all. xsd schema1.xsd schema2.xsd schema3.xsd /c
S
Serge Wautier

xsd.exe as mentioned by Marc Gravell. The fastest way to get up and running IMO.

Or if you need more flexibility/options :

xsd2code VS add-in (Codeplex)


I couldn't get xsd2code to work for me at all. xsd.exe is more robust, but struggles with schemas that have "circular" groups.
xsd2code works in visual studio 2017 and was exactly what i was looking for. you have to run it first in the program files (x86) directory, then use the vsix installer. then it works great. it was FAR SUPERIOUR to the xsd.exe which generated arrays[][] instead of lists.i had a giant .xsd and i need to create classes to serialize the XML into. xsd.exe wouldn't generate serializable code (.net core 2) and xsd2code worked great
Updated version of XSD2CODE for Visual Studio 2015 e 2017 is here: marketplace.visualstudio.com/…
The original xsd2code is now xsd2code++. The community edition is available on VS Marketplace
E
Emil

I show you here the easiest way using Vs2017 and Vs2019 Open your xsd with Visual Studio and generate a sample xml file as in the url suggested.

Once you opened your xsd in design view as below, click on xml schema explorer

2. Within “XML Schema Explorer” scroll all the way down to find the root/data node. Right click on root/data node and it will show “Generate Sample XML”. If it does not show, it means you are not on the data element node but you are on any of the data definition node.

https://i.stack.imgur.com/oVDIV.png

Copy your generated Xml into the clipboard Create a new empty class in your solution and delete the class definition. Only Namespace should remain While your mouse pointer focused inside your class, choose EDIT-> Paste Special-> Paste Xml as Classes


This isn't guaranteed to generate all classes, unfortunately, but it is a COOL trick.
@JohnZabroski did you have any case that it didnt work for you? It depends on sample xml, if you can create sample xml with all classes and members, there is no reason to miss any class and member.
My point is step 2 isnt guaranteed to work. But it is a COOL trick.
Wonderful answer. You deserve some cold beers!!
Cool for simple schemas! But it doesn't help if you have elements line
V
VoteCoffee

xsd.exe does not work well when you have circular references (ie a type can own an element of its own type directly or indirectly).

When circular references exist, I use Xsd2Code. Xsd2Code handles circular references well and works within the VS IDE, which is a big plus. It also has a lot of features you can use like generating the serialization/deserialization code. Make sure you turn on the GenerateXMLAttributes if you are generating serialization though (otherwise you'll get exceptions for ordering if not defined on all elements).

Neither works well with the choice feature. you'll end up with lists/collections of object instead of the type you want. I'd recommend avoiding choice in your xsd if possible as this does not serialize/deserialize well into a strongly typed class. If you don't care about this, though, then it's not a problem.

The any feature in xsd2code deserializes as System.Xml.XmlElement which I find really convenient but may be an issue if you want strong typed objects. I often use any when allowing custom config data, so an XmlElement is convenient to pass to another XML deserializer that is custom defined elsewhere.


I added xsd2code by looking at your answer. Do we need to change anything for it to take care of circular group references ? It is not working for me with default properties
I didn't have to do anything special for it to work with circular references. If you post the xml as a new question and add a link here I'm happy to take a look at it.
c
cnom

For a quick and lazy solution, (and not using VS at all) try these online converters:

xsd-to-xml-converter here

xmltocsharp converter here

XSD => XML => C# classes

Example XSD:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="shiporder">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="orderperson" type="xs:string"/>
      <xs:element name="shipto">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="address" type="xs:string"/>
            <xs:element name="city" type="xs:string"/>
            <xs:element name="country" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="item" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="note" type="xs:string" minOccurs="0"/>
            <xs:element name="quantity" type="xs:positiveInteger"/>
            <xs:element name="price" type="xs:decimal"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="orderid" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

</xs:schema>

Converts to XML:

<?xml version="1.0" encoding="utf-8"?>
<!-- Created with Liquid Technologies Online Tools 1.0 (https://www.liquid-technologies.com) -->
<shiporder xsi:noNamespaceSchemaLocation="schema.xsd" orderid="string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <orderperson>string</orderperson>
  <shipto>
    <name>string</name>
    <address>string</address>
    <city>string</city>
    <country>string</country>
  </shipto>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>3229484693</quantity>
    <price>-6894.465094196054907</price>
  </item>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>2181272155</quantity>
    <price>-2645.585094196054907</price>
  </item>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>2485046602</quantity>
    <price>4023.034905803945093</price>
  </item>
  <item>
    <title>string</title>
    <note>string</note>
    <quantity>1342091380</quantity>
    <price>-810.825094196054907</price>
  </item>
</shiporder>

Which converts to this class structure:

   /* 
    Licensed under the Apache License, Version 2.0

    http://www.apache.org/licenses/LICENSE-2.0
    */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="shipto")]
    public class Shipto {
        [XmlElement(ElementName="name")]
        public string Name { get; set; }
        [XmlElement(ElementName="address")]
        public string Address { get; set; }
        [XmlElement(ElementName="city")]
        public string City { get; set; }
        [XmlElement(ElementName="country")]
        public string Country { get; set; }
    }

    [XmlRoot(ElementName="item")]
    public class Item {
        [XmlElement(ElementName="title")]
        public string Title { get; set; }
        [XmlElement(ElementName="note")]
        public string Note { get; set; }
        [XmlElement(ElementName="quantity")]
        public string Quantity { get; set; }
        [XmlElement(ElementName="price")]
        public string Price { get; set; }
    }

    [XmlRoot(ElementName="shiporder")]
    public class Shiporder {
        [XmlElement(ElementName="orderperson")]
        public string Orderperson { get; set; }
        [XmlElement(ElementName="shipto")]
        public Shipto Shipto { get; set; }
        [XmlElement(ElementName="item")]
        public List<Item> Item { get; set; }
        [XmlAttribute(AttributeName="noNamespaceSchemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
        public string NoNamespaceSchemaLocation { get; set; }
        [XmlAttribute(AttributeName="orderid")]
        public string Orderid { get; set; }
        [XmlAttribute(AttributeName="xsi", Namespace="http://www.w3.org/2000/xmlns/")]
        public string Xsi { get; set; }
    }

}

Attention! Take in account that this is just to Get-You-Started, the results obviously need refinements!


Thank you so much. This can be use as a good example for those who are learning XML Schema and XML in .NET
Wonderful answer. You deserve some cold beers!
h
hdoghmen

I use XSD in a batch script to generate .xsd file and classes from XML directly :

set XmlFilename=Your__Xml__Here
set WorkingFolder=Your__Xml__Path_Here

set XmlExtension=.xml
set XsdExtension=.xsd

set XSD="C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1\Tools\xsd.exe"

set XmlFilePath=%WorkingFolder%%XmlFilename%%XmlExtension%
set XsdFilePath=%WorkingFolder%%XmlFilename%%XsdExtension%

%XSD% %XmlFilePath% /out:%WorkingFolder%
%XSD% %XsdFilePath% /c /out:%WorkingFolder%

M
Melchia

The command that worked in my case was:

xsd /c your.xsd 

A
Aske B.

I used xsd.exe in the Windows command prompt.

However, since my xml referenced several online xml's (in my case http://www.w3.org/1999/xlink.xsd which references http://www.w3.org/2001/xml.xsd) I had to also download those schematics, put them in the same directory as my xsd, and then list those files in the command:

"C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\xsd.exe" /classes /language:CS your.xsd xlink.xsd xml.xsd


That wouldn't happen to be the Amazon market place XSD's you where building classes for now would it :-) I had to work with them once, never again will I touch them or do any work in C# using amazons XSD files, there are such a mess it's unreal.
@shawty I was working with GIS standards - WFS and WMS - which are defined by large, circular cross-referenced XSD's. Was a big mess with xsd.exe because it doesn't like circular references, but I was successful in the end.
yea, that would have been my second guess. Seen those too, thier no where near as bad as Amazons stuff though... gives me nightmares remembering shudders
I
Igoris Azanovas

Marc Gravells answer was right for me but my xsd was with extension of .xml. When I used xsd program it gave :
- The table (Amt) cannot be the child table to itself in nested relations.

As per this KB325695 I renamed extension from .xml to .xsd and it worked fine.


j
jcsilva87

If you want to generate the class with auto properties, convert the XSD to XML using this then convert the XML to JSON using this and copy to clipboard the result. Then in VS, inside the file where your class will be created, go to Edit>Paste Special>Paste JSON as classes.


Awesome answer. Worked much better, IMO.
H
Hamit YILDIRIM

Along with WSDL, I had xsd files. The above did not work in my case gave error. It worked as follows

wsdl /l:C# /out:D:\FileName.cs D:\NameApi\wsdl_1_1\RESAdapterService.wsdl 
D:\CXTypes.xsd D:\CTypes.xsd 
D:\Preferences.xsd