About the XML to C# Converter
The gap between an XML message and a C# class is mostly naming. Elements are usually lower case, properties must be PascalCase, and something has to record the mapping between them. This generator writes that mapping explicitly with [XmlElement("original-name")] on every property and [XmlRoot] on the top class, so XmlSerializer round trips the document without a custom contract.
Types are inferred from the sample values. Whole numbers become int, decimals become double, the words true and false become bool, and repeated elements become List<T> with a class generated for the item shape. Nested elements each get their own class, named after the tag and singularised when the tag is plural, so an invoice with several line children yields an Invoice class holding a List<Line>.
Switch the annotation menu to JsonPropertyName when the same model will be serialised as JSON by System.Text.Json, or to None for a plain DTO with no serialisation opinion at all. Adding a namespace wraps and indents the whole file so it can be pasted into a project as it stands. Note that decimal money values arrive as double here, and swapping them to decimal by hand is worth the minute it takes for financial data. For the JSON equivalent see JSON to C#.
How to use
- Paste a representative XML document, including at least two of any repeating element.
- Choose the annotation style that matches how the class will be serialised.
- Type a namespace to get a complete file rather than bare class declarations.
- Copy the classes or download them as a
.csfile.
Common questions
- Will XmlSerializer read my document with these classes?
- Yes for the element names, because each property carries the original tag in its attribute. Namespaced documents may also need a Namespace argument on the attributes.
- Why is a price typed as double?
- Inference cannot tell money apart from any other decimal. For financial values, change the property to decimal after generating.
- How are attributes in the XML mapped?
- They become ordinary properties. If you need them bound as attributes rather than elements, change XmlElement to XmlAttribute on those lines.
- Can I generate records instead of classes?
- Not here. The output uses classes with get and set accessors, which is what the XML serialiser requires.