GitHub - twpayne/go-xmlstruct: Generate Go structs from multiple XML documents. (original) (raw)

go-xmlstruct

PkgGoDev

Generate Go structs from multiple XML documents.

What does go-xmlstruct do and why should I use it?

go-xmlstruct generates Go structs from XML documents. Alternatively put, go-xmlstruct infers XML schemas from one or more example XML documents. For example, given this XML document, go-xmlstruct generates this Go source code.

Compared to existing Go struct generators likezek,XMLGen, andchidley, go-xmlstruct:

go-xmlstruct is useful for quick-and-dirty unmarshalling of arbitrary XML documents, especially when you have no schema or the schema is extremely complex and you want something that "just works" with the documents you have.

Note the bug in Go's encoding/xml:

Mapping between XML elements and data structures is inherently flawed: an XML element is an order-dependent collection of anonymous values, while a data structure is an order-independent collection of named values. See encoding/json for a textual representation more suitable to data structures.

Install

Install the goxmlstruct CLI with:

$ go install github.com/twpayne/go-xmlstruct/cmd/goxmlstruct@latest

Example

Feed goxmlstruct the simple XML document:

text

by running:

$ echo 'text' | goxmlstruct

This produces the output:

// Code generated by goxmlstruct. DO NOT EDIT.

package main

type Parent struct { Child struct { Flag bool xml:"flag,attr" CharData string xml:",chardata" } xml:"child" }

This demonstrates:

For a full list of options to the goxmlstruct CLI run:

You can run a more advanced example with:

$ git clone https://github.com/twpayne/go-xmlstruct.git $ cd go-xmlstruct $ goxmlstruct internal/tests/gpx/testdata/*.gpx

This demonstrates generating a Go struct from multiple complex XML documents.

For an example of configurable field naming and named types by using go-xmlstruct as a package, seeinternal/tests/rss/rss_test.go.

For an example of a complex schema, seeinternal/tests/aixm/aixm_test.go.

How does go-xmlstruct work?

Similar to go-jsonstruct, go-xmlstruct consists of two phases:

  1. Firstly, go-xmlstruct explores all input XML documents to determine their structure. It gathers statistics on the types used for each attribute, chardata, and child element.
  2. Secondly, go-xmlstruct generates a Go struct based on the observed structure using the gathered statistics to determine the type of each field.

License

MIT