Paste XML as Class in Visual Studio 2017

A very helpful feature in Visual Studio 2017 is Paste Special. You can copy a XML or JSON file to the clipboard and paste a class definition that matches your file. That doesn’t sound like much but it can help you to save a lot of time – especially when your XML file has no namespaces and no schema.

Paste Special was introduced in Visual Studio 2015 and had the same functionality as the equally named feature of Web Essentials. Even when you don’t use Visual Studio 2017, you may be able to use that feature down to Visual Studio 2012.

To show this feature in action, we start with a text that looks like XML:

Now we need a target to paste the class into. The simplest way is to create a new class and remove everything except the namespace declaration:

With the cursor placed where you want to insert the code, you now select the edit menu of Visual Studio, expand Paste Special and click on Paste XML As Classes:

You now have a class that represents your XML file:

This feature works with list and nested items. The generated attributes for ignoring the namespace and schema definition was for me especially helpful. Writing the code on your own is possible, but until you figure out the attributes you need to get the XMLSerializer working may take hours…

With a class in place you now can use the .Net XMLSerializer to read the file into an object:

That’s all you need to know to use this feature.

(If the XML option isn’t showing up and you use an earlier version of Visual Studio 2017 (.0 or .1, try to install the WCF (Windows Communication Foundation) component. For some that was all it took to get that option to show up. As of August 2017 this is no longer needed and worked with the Community Edition of Visual Studio 2017 right out of the box.)

4 thoughts on “Paste XML as Class in Visual Studio 2017”

  1. Great article. How would this work if say I am pulling the xml file down from a URL dynamically? So have like:

    XmlDocument doc = new XmlDocument();
    doc.Load(url);

    How would I load that into the classes?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.