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

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


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.

 

 



If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly.

Also, don't forget to share your views and/or feedback in the comment section below.

0 comments

 
© 2008-2018 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top