Generate C# Class from XML

Dynamics 365 Finance and Operations (D365FO) has data entities to exchange data to/from your own programs. Now what if you want to write a new program that is able to consume one or more D365FO data entities? In just a few lines of code you can connect to a published data entity. But if you want to do more with the values, or even values that could be nested inside a D365FO data entity structure, then I prefer to use a class that is specifically tuned in to that data entity. The D365FO data entity use OData and are able to pass data as JSON or XML. So it is possible to store a message as a file to my hard disk, but then what?

In Visual Studio, you can easily convert JSON or XML text into C# classes. Follow the quick steps:

  1. Copy the JSON or XML text that you want to convert.
  2. Open your project in Visual Studio.
  3. Add a new, empty class file to your solution (you can do this by pressing Shift + Alt + C).
  4. Open the newly created class file.
  5. Go to the Edit menu and select Paste Special.
  6. Choose either Paste JSON As Classes or Paste XML As Classes based on your input.

And what if you want to parse several XML files and have their corresponding C# Classes generated? To do that you can use the xsd.exe tool. Use the following example batch file to generate the classes you need.

@ECHO OFF
REM Date: 22-feb-2022
REM Author: byteway
REM Description: Convert XML file to C# Class

SET XSD="c:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\xsd.exe"
SET SOURCE="d:\Temp\D365FO\CustomerInvoice.xml"

%XSD% %SOURCE%
pause