简体   繁体   中英

Best way to construct XML from JSON in Golang

I have a middleware where I receive JSON input and with user credentials and needs to grab them to construct a full XML with various other data.

Suppose I have below code to decode JSON:

json.NewDecoder(r.Request.Body).Decode(entityPointer)

What is the most efficient way to construct XML from here?

I thought I could just match with struct and use them or parse them with existing XML template and replace the template variables?

if I had for example {username: '11', password: 'pass'} as request, How can I construct below XML out of

You can use the same struct for both XML and JSON, for example:

type Person struct {
    Id        int    `xml:"id,attr"`
    FirstName string `xml:"name>first" json:"first"`
    LastName  string `xml:"name>last" json:"last"`
}

func main() {
    j := `{"id": 10, "first": "firstname", "last":"lastname"}`
    var p Person
    fmt.Println(json.Unmarshal([]byte(j), &p), p)
    out, _ := xml.MarshalIndent(p, "\t", "\t")
    fmt.Println(string(out))

}

playground

Check the xml examples @ http://golang.org/pkg/encoding/xml/#example_Encoder

//edit

Well, since you already have a template you could use html/template , for example :

const xmlTmpl = `<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE api SYSTEM "api.dtd">
<api version="6.0">
    <request>
<reqClient returnToken="N">
    <user>{{.AdminUsername}} </user>
    <password>{{.AdminPassword}}</password>
</reqClient><reqValidate returnBalance="Y">
    <userName>{{.Username}}</userName>
    <password>{{.Password}}</password>
    <channel>M</channel>
</reqValidate></request>
</api>
`

var tmpl = template.Must(template.New("foo").Parse(xmlTmpl))

type Entity struct {
    AdminUsername      string `json:"-"`
    AdminPassword      string `json:"-"`
    Username, Password string
}

func main() {
    e := Entity{Username: "User", Password: "Loser"}
    //json.NewDecoder(r.Request.Body).Decode(&e)
    e.AdminUsername = "admin" // fill admin user/pass after parsing the request
    e.AdminPassword = "admin-password"
    fmt.Println(tmpl.Execute(os.Stdout, e))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM