Sekm
Sekm

Reputation: 1676

How to marshal xml in Go but ignore empty fields

If I have a struct which I want to be able to Marhsal/Unmarshal things in and out of xml with (using encoding/xml) - how can I not print attributes which are empty?

package main

import (
    "encoding/xml"
    "fmt"
)

type MyThing struct {
    XMLName xml.Name `xml:"body"`
    Name    string   `xml:"name,attr"`
    Street  string   `xml:"street,attr"`
}

func main() {
    var thing *MyThing = &MyThing{Name: "Canister"}
    result, _ := xml.Marshal(thing)
    fmt.Println(string(result))
}

For example see http://play.golang.org/p/K9zFsuL1Cw

In the above playground I'd not want to write out my empty street attribute; how could I do that?

Upvotes: 11

Views: 5713

Answers (1)

Grzegorz Żur
Grzegorz Żur

Reputation: 49201

Use omitempty flag on street field.

From Go XML package:

  • a field with a tag including the "omitempty" option is omitted if the field value is empty. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

In case of your example:

package main

import (
    "encoding/xml"
    "fmt"
)

type MyThing struct {
    XMLName xml.Name `xml:"body"`
    Name    string   `xml:"name,attr"`
    Street  string   `xml:"street,attr,omitempty"`
}

func main() {
    var thing *MyThing = &MyThing{Name: "Canister"}
    result, _ := xml.Marshal(thing)
    fmt.Println(string(result))
}

Playground

Upvotes: 12

Related Questions