Generate C# class from XML

235,092

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.

  1. Copy your XML file's content to clipboard
  2. In editor, select place where you want your classes to be pasted
  3. 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.

SimpleXmlToCode

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.

Share:
235,092

Related videos on Youtube

user496949
Author by

user496949

Updated on September 29, 2021

Comments

  • user496949
    user496949 over 2 years

    Can I generate a C# class from an XML file?

  • Nicholas Petersen
    Nicholas Petersen over 10 years
    I 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
    Roger about 10 years
    Was this left out of VS 2013?
  • miszczu
    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
    Jess almost 10 years
    To use xsd run the Developer Command Prompt for VS2013 under your tools menu.
  • Jess
    Jess almost 10 years
    This is much quicker than xsd, but the output is about the same.
  • Julian
    Julian over 9 years
    xsd.exe can be found under: C:\Program Files (x86)\Microsoft SDKs\Windows
  • André Fiedler
    André Fiedler over 9 years
    produces wrong code: // ELEMENTS [XmlIgnore] public DateTime Value { get; set; } [XmlText] public string ValueString { get { return Value ? "true" : "false"; } set { Value = value == "true"; } }
  • André Fiedler
    André Fiedler over 9 years
    And the constructors are unnecessary + you should include comments for publicly visible members
  • Talon
    Talon over 9 years
    In 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
    codechinchilla over 9 years
    I'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
    Elaine over 9 years
    I have only "Paste JSON as Classes"
  • miszczu
    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
    Elaine over 9 years
    @miszczu, it's just solved with pointing to any class in WCF project other than class library.
  • real_yggdrasil
    real_yggdrasil over 9 years
    This 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
    Vikram Singh Saini about 9 years
    I 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
    Clay almost 9 years
    Awesome solution! On top of this if you have Resharper - CTRL+ALT+F (Full cleanup) also makes the generated code readable.
  • drzaus
    drzaus over 8 years
    as @Jess mentioned the output is nearly the same as running xsd -- I noticed pasting omits XmlElementAttribute(Form = ...Unqualified); but I actually don't know if that matters...
  • Jess
    Jess over 8 years
    Hi @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
    drzaus over 8 years
    good call @Jess, schema validation is an important point; also mentioned by Albin's answer stackoverflow.com/a/4203765/1037948
  • Matthew Lock
    Matthew Lock about 8 years
    be warned if you have a large complex XML file the class generated will be so ugly that it will almost be unusable ;)
  • AlexDev
    AlexDev almost 8 years
    If 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
    SvenAelterman almost 8 years
    The 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
    Koray over 7 years
    I 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
    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
    Erdem ÖZDEMİR about 7 years
    If 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
    user1991179 almost 7 years
    For me xsd.exe was found at: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
  • Alex 75
    Alex 75 over 6 years
    It 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
    Tomas Kubes over 5 years
    There is minor difference to XSD output. Special Paste generate numbers automatically, xsd.exe not.
  • Savage
    Savage over 4 years
    Pity it seems to invert the order of classes (outside elements listed last)
  • cantSleepNow
    cantSleepNow almost 4 years
    this 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 or short. 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
    Naikrovek almost 3 years
    I 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
    Anssi over 2 years
    @Naikrovek Yeah and XML is not for everything. :)
  • colinD
    colinD over 2 years
    Just 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.