About the XML to Go Converter
Writing Go structs for an XML feed means remembering two things at once: the exported field name and the tag that maps it back to the original element. This generator handles both. Field names are exported and follow Go naming conventions, including the initialisms the standard style guide insists on, so an id element becomes ID and a url element becomes URL rather than the awkward Id and Url.
Tags are written for encoding/xml and encoding/json together by default, which is what you want for a service that reads XML upstream and serves JSON downstream. The fields are padded into columns so the output already looks like gofmt ran over it. Numeric leaves become int64 or float64 depending on whether the sample value has a decimal point, booleans map to bool, and empty elements fall back to interface{} because nothing in the sample says what they hold.
Repeated elements become slices of a generated struct, with the type name singularised so a list of sensor elements is a []Sensor and not a []Sensors. Turning on pointer fields makes nested structs pointers, which lets you tell an absent block apart from a present but empty one. Bear in mind that encoding/xml needs XMLName and attribute tags for some documents, so treat this output as the starting point rather than the last word. For JSON input, JSON to Go does the same job.
How to use
- Paste an XML sample that shows every field you care about.
- Pick the struct tags you need. Both xml and json is the safe default for a service that speaks each.
- Set a package name so the snippet compiles as a file rather than a fragment.
- Copy the structs into your project and adjust any field you know is optional.
Common questions
- Why is a field called ID rather than Id?
- Go style capitalises known initialisms such as ID, URL, API and HTTP. The struct tag still carries the original element name.
- Do I need to add XMLName myself?
- Often yes. If the root element name matters to the decoder, add an XMLName field with the appropriate tag to the top struct.
- What happens to an empty element?
- It becomes interface{} because the sample gives no clue about its type. Replace it with a concrete type once you know.
- Is the output gofmt clean?
- Fields are aligned in the gofmt style, though running gofmt on the file after pasting is still a sensible habit.