
XML to Go Struct
Turn an XML sample into Go structs with encoding/xml tags.
Runs in your browser. Nothing you type is uploaded.
How the converter works
Paste an XML sample and the Go code appears as you type. Every element that has attributes or child elements becomes a struct; elements that only hold text become plain fields. Names are converted to exported Go names (in_stock becomes InStock, id becomesID) and each field gets an xml tag with the original name, soencoding/xml can fill it straight from your data.
<book id="1"><title>Dune</title></book>
import "encoding/xml"
type Book struct {
XMLName xml.Name `xml:"book"`
ID int `xml:"id,attr"`
Title string `xml:"title"`
}How XML maps to struct tags
- An attribute gets
xml:"id,attr". - A child element gets
xml:"title". Several siblings with the same name become a slice such as[]Book, and the field is named in the plural. - Text inside an element that also has attributes or children goes in a field tagged
xml:",chardata". - The root gets an
XMLName xml.Namefield so the struct can be marshalled back to XML. Untick the option to leave it out. - Attributes and elements missing from some of the repeated elements get
omitempty, and an optional child with its own struct becomes a pointer.
How types are chosen
Every value seen is checked: true and false become bool, whole numbers become int (or int64 when too big for 32 bits), numbers with a fraction become float64, and everything else is a string. If the values for one field disagree (say 9.99 in one book and n/a in another) it falls back tostring. Values like 007 stay strings so leading zeros are not lost.
Using the structs
var b Book
if err := xml.Unmarshal(data, &b); err != nil {
log.Fatal(err)
}FAQ
What about namespaces?
Prefixes are removed and xmlns declarations are skipped. Without a namespace in the tag,encoding/xml matches the local name in any namespace, which is what most feeds need. Add the namespace to a tag yourself if two namespaces use the same local name.
Is the output exactly what I should ship?
It is a good starting point, but one sample cannot show everything. Check which fields are really optional, use int64 for large IDs, and consider time.Time for dates. Comments, processing instructions and DOCTYPE declarations are ignored.
Is my XML sent anywhere?
No. The conversion runs in your browser, so your data stays on your device.
Need JSON instead? JSON to Go struct is on our sister site JSON Nerd.
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 C# class: Generate C# classes with XmlSerializer attributes from an XML sample.
- XML sitemap generator: Turn a list of URLs into a sitemap.xml file for search engines.