go - Golang Hide XML parent tag if empty -
after trail , error i'd share issue dealing with.
i'm populating struct , convert xml ( xml.marshal ) can see below foo example works expected. bar example creates empty group1.
so question : "how prevent group1 generated if there no children set."
package main  import (     "fmt"     "encoding/xml" )  type example1 struct{     xmlname  xml.name `xml:"example1"`     element1 string   `xml:"group1>element1,omitempty"`     element2 string   `xml:"group1>element2,omitempty"`     element3 string   `xml:"group2>example3,omitempty"` }  func main() {     foo := &example1{}     foo.element1 = "value1"      foo.element2 = "value2"      foo.element3 = "value3"       fooout, _ := xml.marshal(foo)     fmt.println( string(fooout) )      bar  := &example1{}     bar.element3 = "value3"     barout, _ := xml.marshal(bar)     fmt.println( string(barout) ) }   foo output :
<example1>     <group1>         <element1>value1</element1>         <element2>value2</element2>     </group1>     <group2>         <example3>value3</example3>     </group2> </example1>   bar output :
<example1>     <group1></group1>  <------ how remove empty parent value ?      <group2>         <example3>value3</example3>     </group2> </example1>   addition
additionally have tried doing following, still generates empty "group1":
type example2 struct{     xmlname  xml.name `xml:"example2"`     group1   struct{         xmlname  xml.name `xml:"group1,omitempty"`         element1 string   `xml:"element1,omitempty"`         element2 string   `xml:"element2,omitempty"`     }     element3 string   `xml:"group2>example3,omitempty"` }   the full code can found here : http://play.golang.org/p/shicbholcg . example
edit : changed golang example use marshalindent readability
edit 2 example ainar-g works hiding empty parent, populating makes lot harder.  "panic: runtime error: invalid memory address or nil pointer dereference"
example1 doesn't work because apparently ,omitempty tag works on element , not a>b>c enclosing elements.
example2 doesn't work because ,omitempty doesn't recognise empty structs empty. from doc:
the empty values false, 0, nil pointer or interface value, , array, slice, map, or string of length zero.
no mention of structs. can make baz example work changing group1 pointer struct:
type example2 struct {     xmlname  xml.name `xml:"example1"`     group1   *group1     element3 string `xml:"group2>example3,omitempty"` }  type group1 struct {     xmlname  xml.name `xml:"group1,omitempty"`     element1 string   `xml:"element1,omitempty"`     element2 string   `xml:"element2,omitempty"` }   then, if want fill group1, you'll need allocate separately:
foo.group1 = &group1{     element1: "value1", }   example: http://play.golang.org/p/mgpi4oshf7
Comments
Post a Comment