question:
golang encoding/xml: foo>bar,attr - foo ignored
solution:
you can replace output result to add attr for foo
package main
//warning: go version must >=1.6
import (
"bytes"
"encoding/xml"
"fmt"
//"runtime"
)
type Test struct {
Play Play
//Name CdataString `xml:"Play>Name"`
Vast string `xml:"vast,attr"`
Ad string `xml:""`
}
type Play struct {
//Id string `xml:"id,attr"`
Name CdataString `xml:"Name"`
}
type CdataString struct {
Value string `xml:",cdata"`
}
func main() {
//fmt.Println(runtime.Version())
name := CdataString{Value: "bbbccc"}
//v := &Test{Id: "111", Play: Play{Id: "111", Name: name}}
v := &Test{Play: Play{Name: name}}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
//add skipoffset=”00:00:05” for Play
output = bytes.Replace(output, []byte("<Play>"), []byte(`<Play skipoffset="00:00:05">`), -1)
fmt.Println(string(output))
}
other issues :
https://github.com/golang/go/issues/3688
refer doc :
https://golang.org/pkg/encoding/xml/#pkg-examples
https://play.golang.org/p/KN6MWrvFJD
// xmltest.go
package main
import (
"encoding/xml"
"fmt"
"time"
)
type Request struct {
XMLName xml.Name `xml:"root"`
Login string `xml:"login"`
Password string `xml:"password"`
From string `xml:"getBookings>from,attr"`
Location string `xml:"getBookings>location,attr"`
}
type WorkAround struct {
XMLName xml.Name `xml:"root"`
Login string `xml:"login"`
Password string `xml:"password"`
GetBookings struct {
From time.Time `xml:"from,attr"`
Location string `xml:"location,attr"`
} `xml:"getBookings"`
}
func main() {
raw := []byte(`
<root>
<login>test</login>
<password>password</password>
<getBookings from="2011-01-01T12:00:00Z" location="30038">
</root>`)
fmt.Printf("Original Data: %s\n", string(raw))
r, w := &Request{}, &WorkAround{}
xml.Unmarshal(raw, r) // Check removed for brevity
xml.Unmarshal(raw, w) // Check removed for brevity
fmt.Printf("Unmarshalled Data: %+v\n", r)
fmt.Printf("Unmarshalled Workaround: %+v\n", w)
mr, _ := xml.MarshalIndent(r, "", "\t") // Check removed for brevity
mw, _ := xml.MarshalIndent(w, "", "\t") // Check removed for brevity
fmt.Printf("Marshalled Data: %s\n\nUsing Workaround: %s\n\n", mr, mw)
fmt.Printf("Bug fixed: %t\n", string(mr) == string(mw))
}
code2:
https://play.golang.org/p/VE74VQoJ7c
// xmltest.go
package main
import (
"encoding/xml"
"fmt"
"time"
)
// Original failing struct
/*
type WSRequest struct {
XMLName xml.Name `xml:"root"`
Login string `xml:"login"`
Password string `xml:"password"`
From string `xml:"getBoo