liveBook · Manning

Encoding/xml

As explained in Go in Action, Second Edition

encoding/xml is a Go standard-library package for encoding and decoding XML documents.

encoding/xml is Go’s standard-library package for converting XML documents and Go values. Define structs with XML tags, then use Marshal or Unmarshal to serialize or parse data. Its tag syntax also maps attributes, namespaces, comments, and structured elements. section 10.5.2 section 10.11

A configuration model shared by JSON and XML

A Config struct can map Name and Version to XML attributes, Namespace to an optional namespace attribute, Debug and Port to elements, and Comment to an XML comment. Adding JSON tags to the same fields lets one Go type support both representations. section 10.5.2

.Defining a configuration structure with XML tags
[source,go,linenums]
----
type Config struct {
    XMLName   xml.Name `xml:"configuration"` // Root element name
    Name      string   `json:"name" xml:"name,attr"` // XML attribute
    Version   string   `json:"version" xml:"version,attr"` // XML attribute
    Namespace string   `xml:"xmlns,attr,omitempty"` // XML namespace
    Debug     bool     `json:"debug" xml:"debug"`
    Port      int      `json:"port" xml:"port"`
    Host      string   `json:"host" xml:"host,omitempty"`
    Comment   string   `xml:",comment"` // XML comment
}
----

Inspect the complete Config definition and its XML field tags. section 10.5.2

A conversion pipeline parses input into an intermediate Go struct, then marshals that validated and normalized representation into the requested format. This composes with file, network, and in-memory I/O in a larger CLI tool. section 10.5.2 section 10.10

How Go in Action, Second Edition covers it

How deep it goes
Explains struct tags, attributes, namespaces, comments, and conversion flow, while stopping short of exhaustive XML API coverage.
Examples
Uses a Config struct and a JSON-to-XML conversion function within a validation and conversion CLI.
What you can do after
Build XML serialization and parsing with Go structs, XML tags, and the encoding/xml Marshal and Unmarshal functions.
How it connects
Connects XML serialization with Go structs, struct tags, JSON, validation, normalization, and composable I/O.

Also explained in

Compare how 2 books explain encoding/xml →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.