XML to Go structs
Go's standard library decodes XML with encoding/xml, using struct tags to say whether a field comes from an attribute, a child element or the element's text. This XML to Go generator infers the struct layout and field types from a sample document. It writes json tags, since it models the JSON form of the data, so the one step left is to turn them into xml tags, as shown below.
Example: a server configuration
<server name="api-1">
<listen port="8080" tls="false"/>
<route path="/users" method="GET">users.List</route>
<route path="/users" method="POST">users.Create</route>
<timeout>30</timeout>
</server>
type Server struct {
Listen Listen `json:"listen"`
Route []Route `json:"route"`
Timeout int64 `json:"timeout"`
Name string `json:"name"`
}
type Listen struct {
Port int64 `json:"port"`
TLS bool `json:"tls"`
}
type Route struct {
Value string `json:"value"`
Path string `json:"path"`
Method string `json:"method"`
}
Converting the tags for encoding/xml
type Server struct {
XMLName xml.Name `xml:"server"`
Name string `xml:"name,attr"`
Listen Listen `xml:"listen"`
Route []Route `xml:"route"`
Timeout int64 `xml:"timeout"`
}
type Route struct {
Path string `xml:"path,attr"`
Method string `xml:"method,attr"`
Value string `xml:",chardata"`
}
,attrmarks an attribute; the generator does not distinguish attributes from elements, so check the original XML for each field.,chardatamaps the element's text, which the generator namesValue.- A slice with
xml:"route"collects repeated<route>children. XMLNamechecks the root element name; it is optional.
Then decode with xml.Unmarshal(data, &server); encoding/xml converts attribute and element text to int64 and bool for you.
Streaming large XML files
xml.Unmarshal reads the whole document into memory. For large exports, create an xml.NewDecoder(file), loop over decoder.Token(), and when you reach a StartElement named route, call decoder.DecodeElement(&route, &start) to decode just that element into the generated Route struct. Memory use then stays constant no matter how many records the file contains.
Pitfalls
- Elements that repeat must appear at least twice in the sample to become slices. If the sample mixes one and many, the generator creates a wrapper struct with a pointer and a slice field; simplify it to a slice for XML.
- Namespace prefixes are removed in field names.
encoding/xmlmatches on local names by default, so tags usually work without them. - Leading zeros in numeric-looking text are lost when typed
int64; usestringfor codes.
For JSON APIs, JSON to Go generates structs with ready-to-use json tags. Inspect the XML with the XML Viewer or tidy it with the XML Formatter. Generation runs in your browser.