Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to marshal xml in Go but ignore empty fields

Tags:

go

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?

like image 276
Sekm Avatar asked Sep 07 '15 10:09

Sekm


1 Answers

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

like image 149
Grzegorz Żur Avatar answered Nov 05 '22 10:11

Grzegorz Żur