Generate Classes from XML in Microsoft Visual Studio 2019

We can create a class from given XML in Microsoft Visual Studio 2019. That means, we can copy the XML and can paste it as C# class in VS 2019.

Let’s consider following XML and copy it (Ctrl + C).

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <Id>1</Id>
    <Name>Raj</Name>
  </Employee>
  <Employee>
    <Id>2</Id>
    <Name>David</Name>
  </Employee>
  <Employee>
    <Id>3</Id>
    <Name>John</Name>
  </Employee>
  <Employee>
    <Id>4</Id>
    <Name>Bob</Name>
  </Employee>
</Employees>

Open Microsoft Visual Studio 2019 => Create new console application. Add new C# class to the solution and name it as Employees.cs.

Copy the above XML (Ctrl + C) and on Visual Studio, go to Edit => Paste Special => select “Paste XML As Classes” as shown below.

It creates the Employees class, as shown below.

// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Employees
{

    private EmployeesEmployee[] employeeField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Employee")]
    public EmployeesEmployee[] Employee
    {
        get
        {
            return this.employeeField;
        }
        set
        {
            this.employeeField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class EmployeesEmployee
{

    private byte idField;

    private string nameField;

    /// <remarks/>
    public byte Id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }

    /// <remarks/>
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }
}

Even we can create a class from JSON response also by selecting “Paste JSON As Classes”.