289

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

1

10 Answers 10

489

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
Sign up to request clarification or add additional context in comments.

18 Comments

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 I haven't used VS 2013, but I think this feature should be there, make sure your project is targeting .NET 4.5 Framework
This is much quicker than xsd, but the output is about the same.
Awesome solution! On top of this if you have Resharper - CTRL+ALT+F (Full cleanup) also makes the generated code readable.
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`
|
373

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.

6 Comments

To use xsd run the Developer Command Prompt for VS2013 under your tools menu.
xsd.exe can be found under: C:\Program Files (x86)\Microsoft SDKs\Windows
be warned if you have a large complex XML file the class generated will be so ugly that it will almost be unusable ;)
For me xsd.exe was found at: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
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.
|
63

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

5 Comments

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.
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.
@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.
Pity it seems to invert the order of classes (outside elements listed last)
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.
23

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: SimpleXmlToCode

Please make suggestions if you like it.

4 Comments

produces wrong code: // ELEMENTS [XmlIgnore] public DateTime Value { get; set; } [XmlText] public string ValueString { get { return Value ? "true" : "false"; } set { Value = value == "true"; } }
And the constructors are unnecessary + you should include comments for publicly visible members
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.
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.
6

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.

Comments

6

You can use xsd as suggested by Darin.

In addition to that it is recommended to edit the test.xsd-file to create a more reasonable schema.

type="xs:string" can be changed to type="xs:int" for integer values
minOccurs="0" can be changed to minOccurs="1" where the field is required
maxOccurs="unbounded" can be changed to maxOccurs="1" where only one item is allowed

You can create more advanced xsd-s if you want to validate your data further, but this will at least give you reasonable data types in the generated c#.

Comments

2

Use below syntax to create schema class from XSD file.

C:\xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\

1 Comment

To use xsd.exe we will have to use command C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools>xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\
2

Found this site a bit ago. It converts XML and JSON to C# and Java classes. Has several options to tweak as you need. I use it pretty often. https://json2csharp.com/xml-to-csharp

Comments

0

To convert XML into a C# Class:

  • Navigate to the Microsoft Visual Studio Marketplace: -- https://marketplace.visualstudio.com
  • In the search bar enter text: -- xml to class code tool
  • Download, install, and use the app

Note: in the fullness of time, this app may be replaced, but chances are, there'll be another tool that does the same thing.

Comments

0

Can use xsd.exe to convert and for that we will have to use command in cmd

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools>xsd C:\Test\test-Schema.xsd /classes /language:cs /out:C:\Test\

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.