I want to create JSON from XML vice versa, so I got stuck at the point if XML contains the attributes e.g. <name id = "12"> Stack <name>
so if this type of XML came how can I solve it.
I have searched on the internet I got this code from this site but it doesn't fill my requirement
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
)
type DataFormat struct {
ProductList []struct {
Sku string `xml:"sku" json:"sku"`
Quantity int `xml:"quantity" json:"quantity"`
} `xml:"Product" json:"products"`
}
func main() {
xmlData := []byte(`<?xml version="1.0" encoding="UTF-8" ?>
<ProductList>
<Product>
<sku >ABC123</sku>
<quantity>2</quantity>
</Product>
<Product>
<sku>ABC123</sku>
<quantity>2</quantity>
</Product>
</ProductList>`)
data := &DataFormat{}
err := xml.Unmarshal(xmlData, data)
if nil != err {
fmt.Println("Error unmarshalling from XML", err)
return
}
result, err := json.Marshal(data)
if nil != err {
fmt.Println("Error marshalling to JSON", err)
return
}
fmt.Printf("%s\n", result)
}
this solution is working on a given sample XML but failed if the XML tag has attributes.
what do I need to modify in this code so that it works for XML which has attributes?
Edit solution:
From the comment i got to know that i need to add atrr and omitempty option then it will work and for marking of attributes i can use @ or $
sample code modification would be for my question:
type DataFormat struct {
ProductList []struct {
Id string `xml:"id,attr,omitempty" json:"@id,omitempty"`
Sku string `xml:"sku" json:"sku"`
Quantity int `xml:"quantity" json:"quantity"`
} `xml:"Product" json:"products"`
}
Thanks for the explanation.