I try to parse an XML data to a JSON file, but when I begin writing marshaled data to a JSON, it just rewrites data in the JSON file and, as a result, I have the file with last XML element. How to write the whole data into the JSON file?
Snippet of code that parses XML and marshal data to JSON
decoder := xml.NewDecoder(file)
resultData := map[string]map[string]string{}
for {
t, _ := decoder.Token()
if t == nil {
break
}
switch et := t.(type) {
case xml.StartElement:
if et.Name.Local == "profile" {
var object XMLProfile
decoder.DecodeElement(&object, &et)
resultData = map[string]map[string]string{
object.ProfileName: {},
}
for _, val := range object.Fields {
resultData[object.ProfileName][val.Name] = val.Value
}
}
}
}
if out, err := json.MarshalIndent(resultData, "", "\t"); err != nil {
panic(err)
} else {
_ = ioutil.WriteFile("test.json", out, 0644)
}
Expect JSON:
{
"Profile 1": {
"role": "user"
},
"Profile 2": {
"role": "user"
},
"Profile 3": {
"role": "admin"
}
}
Actual JSON:
{
"Profile 3": {
"role": "admin"
}
}