XML Nerd
A cartoon tree frog in round glasses, thinking

XML to C# Class

Turn an XML sample into C# classes for XmlSerializer.

Runs in your browser. Nothing you type is uploaded.

How the converter works

Paste an XML sample and the C# code appears as you type. Every element that has attributes or child elements becomes a class with auto-properties; elements that only hold text become plain properties. Names are converted to PascalCase (in_stock becomes InStock) and each property carries the System.Xml.Serialization attribute that maps it back to the original name.

<book id="1"><title>Dune</title></book>

using System.Xml.Serialization;

[XmlRoot("book")]
public class Book
{
    [XmlAttribute("id")]
    public int Id { get; set; }

    [XmlElement("title")]
    public string Title { get; set; }
}

How XML maps to attributes

  • The root class gets [XmlRoot("name")].
  • An attribute gets [XmlAttribute("id")], and a child element gets [XmlElement("title")].
  • Several siblings with the same name become a List<T> property in the plural (Books), tagged with the singular element name so the list is read without a wrapper element.
  • Text inside an element that also has attributes or children goes in a property tagged [XmlText].
  • Optional child elements holding numbers or booleans become nullable (int?). Attributes stay plain, because XmlSerializer does not support nullable attributes.

How types are chosen

Every value seen is checked: true and false become bool, whole numbers become int (or long when too big), numbers with a fraction becomedouble, and everything else is a string. If the values for one field disagree it falls back to string. Values like 007 stay strings so leading zeros are not lost.

Using the classes

var serializer = new XmlSerializer(typeof(Book));
using var reader = new StringReader(xml);
var book = (Book)serializer.Deserialize(reader);

FAQ

What about namespaces?

Prefixes are removed and xmlns declarations are skipped, so the output suits XML without a namespace. If your XML uses one, add Namespace = "..." to the attributes, or the serializer will not find the elements.

Is this the same as xsd.exe?

No. xsd.exe works from a schema, this works from a sample, so it can only guess which elements are optional or repeated. It produces shorter, readable classes you can edit.

Is my XML sent anywhere?

No. The conversion runs in your browser, so your data stays on your device.

More XML tools

  • XML formatter: Format, minify and validate XML in one place.
  • XML validator: Check that XML is well-formed and find the exact line and column of an error.
  • XML beautifier: Pretty print XML with 2 spaces, 4 spaces or tabs.
  • XML minifier: Strip the whitespace between tags to make XML as small as possible.
  • XML to Go struct: Generate Go structs with encoding/xml tags from an XML sample.
  • XML sitemap generator: Turn a list of URLs into a sitemap.xml file for search engines.