During application development, we often use XML files. To use XML files, we need XML objects; and to create the XML objects, we need to write the classes and properties based on the XML nodes/attributes, which we do manually.

 

Do you know that Visual Studio already provides an option to automatically create the entire class structure based on the XML input? Let's discuss this today.

 

Do you know that you can automatically create classes from XML in Visual Studio?

 

There exists many developers who are still not aware of this Visual Studio tricks, and thus spend a lot of their times creating and maintaining the classes & properties require to create the XML mapping. This manual process is no doubt a time consuming process and it's also error prone.

 

Visual Studio 2015 and Visual Studio 2017 provides a menu item which allows you to create the entire class structure from the XML. To do this, you will first need to copy the content of the XML and navigate to Visual Studio Edit menu and then to Paste Special | Paste XML as Classes. Make sure that a blank class file has been already loaded into the Visual Studio editor window as active document.

 

Let's take the following XML as input document. We will be using this XML to create the XML mapping classes automatically from Visual Studio.

 

<?xml version="1.0"?>
<Catalog>
    <Book ID="BK201701" ISBN="9781787281905">
     <Title>Mastering Visual Studio 2017</Title>
     <Author>
         <Name>Kunal Chowdhury</Name>
         <Blog URL="https://kunal-chowdhury.com"/>
     </Author>
    </Book>
    <Book ID="BK201802" ISBN="9781788399807">
        <Title>Windows Presentation Foundation Cookbook</Title>
        <Author>
            <Name>Kunal Chowdhury</Name>
            <Blog URL="https://kunal-chowdhury.com"/>
        </Author>
    </Book>
</Catalog>

 

To do this, first create a class file (.cs) inside the Solution Explorer and then open the file within Visual Studio Editor window. Clear the content of the file. Once the XML content has been copied, navigate to Edit | Paste Special | Paste XML as Classes, as shown in the below screenshot:

 

Here's how to automatically create classes from XML in Visual Studio

 

Within a moment, all your classes will be ready for you to use. Similarly, you can create classes from JSON file content using Visual Studio.

 

 

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.