Generate C# class from XML
Solution 1
Yes, by using xsd.exe
D:\temp>xsd test.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.xsd'.
D:\temp>xsd test.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.cs'.
Notes
Answer how to change directory in Developer Command Prompt to d:\temp may be useful.
If you generate classes for multi-dimensional array, there is a bug in XSD.exe generator, but there are workarounds.
Solution 2
If you are working on .NET 4.5 project in VS 2012 (or newer), you can just Special Paste your XML file as classes.
- Copy your XML file's content to clipboard
- In editor, select place where you want your classes to be pasted
- From the menu, select
EDIT > Paste Special > Paste XML As Classes
Solution 3
At first I thought the Paste Special was the holy grail! But then I tried it and my hair turned white just like the Indiana Jones movie.
But now I use http://xmltocsharp.azurewebsites.net/ and now I'm as young as ever.
Here's a segment of what it generated:
namespace Xml2CSharp
{
[XmlRoot(ElementName="entry")]
public class Entry {
[XmlElement(ElementName="hybrisEntryID")]
public string HybrisEntryID { get; set; }
[XmlElement(ElementName="mapicsLineSequenceNumber")]
public string MapicsLineSequenceNumber { get; set; }
Solution 4
I realise that this is a rather old post and you have probably moved on.
But I had the same problem as you so I decided to write my own program.
The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.
It is in no way elegant but it did the job for me.
You can get it here: Please make suggestions if you like it.
Solution 5
You should consider svcutil (svcutil question)
Both xsd.exe and svcutil operate on the XML schema file (.xsd). Your XML must conform to a schema file to be used by either of these two tools.
Note that various 3rd party tools also exist for this.
Related videos on Youtube
user496949
Updated on September 29, 2021Comments
-
user496949 over 2 years
Can I generate a C# class from an XML file?
-
Wai Ha Lee over 5 yearsPossible duplicate of How to generate .NET 4.0 classes from xsd?
-
-
Nicholas Petersen over 10 yearsI just wish this generated auto-implemented properties, like it does for "Paste JSON as Classes". Currently this means a 6 fold bloated code result, which is a lot harder to read. This alone makes me look for another tool, unfortunately.
-
Roger about 10 yearsWas this left out of VS 2013?
-
miszczu about 10 years@Roger I haven't used VS 2013, but I think this feature should be there, make sure your project is targeting .NET 4.5 Framework
-
Jess almost 10 yearsTo use
xsd
run the Developer Command Prompt for VS2013 under your tools menu. -
Jess almost 10 yearsThis is much quicker than
xsd
, but the output is about the same. -
Julian over 9 years
xsd.exe
can be found under:C:\Program Files (x86)\Microsoft SDKs\Windows
-
André Fiedler over 9 yearsproduces wrong code: // ELEMENTS [XmlIgnore] public DateTime Value { get; set; } [XmlText] public string ValueString { get { return Value ? "true" : "false"; } set { Value = value == "true"; } }
-
André Fiedler over 9 yearsAnd the constructors are unnecessary + you should include comments for publicly visible members
-
Talon over 9 yearsIn my defense it was something I slapped together very quickly which worked for me. I haven't gone back to it but feel free to contribute to the repo any changes.
-
codechinchilla over 9 yearsI've been using this for a few months - it's not perfect, but it's quite useful and I find it generates much more readable/simpler XML than VS2013's paste as XML. Much appreciated Talon.
-
Elaine over 9 yearsI have only "Paste JSON as Classes"
-
miszczu over 9 years@Elaine are you sure you are working on NET 4.5 project? Your projects property 'Target framework' should be set to .NET Framework 4.5
-
Elaine over 9 years@miszczu, it's just solved with pointing to any class in WCF project other than class library.
-
real_yggdrasil over 9 yearsThis is soo helpfull! One addition: You must first create a class (like class1.cs and do the paste special in there. After this action, you can rename to the desired name.
-
Vikram Singh Saini about 9 yearsI would like the text Copy your XML file to clipboard to modified to Copy your XML file's content to clipboard. Because that way I was able to make it work. Else the option show as disabled.
-
Clay almost 9 yearsAwesome solution! On top of this if you have Resharper - CTRL+ALT+F (Full cleanup) also makes the generated code readable.
-
drzaus over 8 yearsas @Jess mentioned the output is nearly the same as running
xsd
-- I noticed pasting omitsXmlElementAttribute(Form = ...Unqualified)
; but I actually don't know if that matters... -
Jess over 8 yearsHi @drzaus. Funny I was just using
xsd
the other day. This time it was very useful b/c the XML was huge and I can do schema validation. -
drzaus over 8 yearsgood call @Jess, schema validation is an important point; also mentioned by Albin's answer stackoverflow.com/a/4203765/1037948
-
Matthew Lock about 8 yearsbe warned if you have a large complex XML file the class generated will be so ugly that it will almost be unusable ;)
-
AlexDev almost 8 yearsIf you don't have resharper use regex replace with
public (\w+) (\w+)\r\n +\{\r\n +get\r\n +\{\r\n +return this.*;\r\n +\}\r\n +set\r\n +\{\r\n +this.*;\r\n +\}\r\n +\}\r\n
=>public $1 $2 { get; set; }
and ` private \w+ \w+Field;\r\n\r\n` -
SvenAelterman almost 8 yearsThe output of this tool is nice, but I just want to make throw a word of caution out there not to submit any sensitive data to this site (or any other for that matter). While I appreciate the service that is offered, there is no privacy policy and little to no assurance that what you paste won't be logged and examined, etc.
-
Koray over 7 yearsI had an xml file that has some recursive relations (maybe it's called circular relation, I'm not sure.) The others failed but xmltocsharp.azurewebsites.net was very successful on that xml.
-
Harag over 7 years@D.Kermott thanks for the website link, I've had a quick look at it and it looks like it does a much better job than the paste special, the code looks cleaner, though my test xml created more classes, it was much nicer to use.
-
Erdem ÖZDEMİR about 7 yearsIf you have an xsd file, open XML Schema Explorer window. Then right click to the root element and click Generate Sample Xml and do the above Special Paste. It works so simple.
-
user1991179 almost 7 yearsFor me
xsd.exe
was found at:C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
-
Alex 75 over 6 yearsIt generates nice classes with many attributes correctly set as boolean, integer, float but it does not work properly in some cases. It sdoes not work for me when I have <ElementA xsi:type="MyElementA" ... >. The error using XML Deserialize is "MyElementA not defined" (or similar). Only using xsd.exe I have all the proper classes defined correctly and XML deserialization works. Unfortunately all the properties are set as string (you have just to change the type manually in the generated class) and many elelemts are defined as array (again manual changes to have only one element).
-
Tomas Kubes over 5 yearsThere is minor difference to XSD output. Special Paste generate numbers automatically, xsd.exe not.
-
Savage over 4 yearsPity it seems to invert the order of classes (outside elements listed last)
-
cantSleepNow almost 4 yearsthis is nice and easy but say that you are getting xml reply from some http call. And in that particular xml a certain values are always 2 digit (for sake of example) the "paste" will make that field
byte
orshort
. And then one day, you call the rest api and in you get a well formed xml, but that value is all of sudden 123456789. I think everyone gets where I'm going ;) -
Naikrovek almost 3 yearsI have a 7GB XML file (it is being used as a human-readable transform of a binary data transfer mechanism in this case) and xsd.exe runs out of memory trying to read that pretty quickly. Note that this is not an out of memory condition on the machine itself; there is plenty of RAM in this machine (192GB) and xsd.exe uses no more than 4 before it dies. So this solution won't be the answer for everyone.
-
Anssi over 2 years@Naikrovek Yeah and XML is not for everything. :)
-
colinD over 2 yearsJust want to point out that this tool doesn't properly set the Form property of the
XmlElement
attribute. This make the standard .NET xml serializer fail silently (no error, but creates an empty object). So if the xml mix elements with and without namespaces, you will need to update the code accordingly. The xsd.exe tool handles this properly.