Today I just faced a situation where I have got a huge XSD library to use for service integration. Because I suspected it won’t be a small task to write by myself and honestly I never had to do this before I started to look for an automated solution.
Being a lazy programmer and having a lazy community I was lucky enough to find this nice XML Schema Definition Tool written by Microsoft.
If you installed Visual Studio you can find this tool under these locations (StackOverflow URL).
In my case it was here
C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools
After I found it I placed this location to my PATH environment variable so I was able to start the xsd.exe from the command prompt.
Once I had all these done I went to the folder that contained all the XSD files and opened the command prompt from there. A useful suggestion: you can open the command prompt straight from the file explorer. If you replace the current file path with “cmd” and you hit enter it will open up the cmd with the current path.
The next step is to write
xsd /classes yourXSDFile.xsd
With this, it will generate the object graph in a .cs file for you to use in your C# application. In my case, it generated for one file only 21000 lines. It would have been a real time consuming manual process. Also, I had to do a lot more than 1 or 2. It will name your .cs file it after your XSD file. In the example above it will be yourXSDFile.cs.
If you have more than a simple XSD file and you have all the XSD files in one folder you have to run this code for each one, one by one. It will find the references to create your root object, but it will generate the entire object graph into one single file, so you will probably have a lot of duplicate references across your generated files. It won’t insert a namespace in so you have to edit your .cs yourself and wrap it into a namespace if you want use all your classes without conflicts but it is just a choice of you, it is not mandatory. Except if your project won’t compile because of duplicate references.
The generated files will “using System.Xml.Serialization;”. It will use all the necessary attributes for you to be able to use the XmlSerializer to translate data between XML and C# object.
You can use this tool for a lot of other things too, but I faced this situation and I wanted to share this with you.
I hope you will make use of it too as I did. If you have any suggestions leave a comment below.