Working with XML in C#

So, this is a post I’ve been meaning to write pretty much since I started the blog. In my adventures in programming I come across XML formats every now and then and I always forget how to create C# classes out of them. Instead of trying to find it on Google the next time, I’ll just read this post instead.

So, let’s say we have an XML file looking like this:

<?xml version="1.0" encoding="utf-8"?>
<Record>
<RecordArtist>Oasis</RecordArtist>
<RecordName>Be Here Now</RecordName>
<RecordYear>1997</RecordYear>
<RecordLabel>Creation Records</RecordLabel>
</Record>

Pretty simple structure, right? Let’s go through the motions of creating a class for this. First, you’ll need to convert the XML to XSD. Find the “Developer Command Prompt for VS 2019” and browse to where the above XML is located.

xsd.exe Record.xml

That’s it! Now you’ve got a XSD that can be used to create a C# class.
To create the class, go:

xsd.exe Record.xsd /c /n:RecordNamespace

Done! Use it in your project and you’re all set.

EDIT: A word of caution: You should always prefer having an XSD to start with instead of an XML. If the XML file doesn’t have all the fields they, naturally, won’t show up in the created class. But you already knew that.

Leave a Reply

Your email address will not be published. Required fields are marked *