'How to get more error detailing when doing Go's unmarshalling for XML files?
I'm pretty new to Golang, but picking things up pretty quickly. I'm developing a tool that involves parsing schemas represented in XML. Intuitively, I've been using Go's xml.Unmarshal from the standard library to avoid having to write my own parser.
However, when the unmarshal function fails, I noticed that it doesn't really go into detail on where or what line it failed. This is pretty troublesome if the XML schema is hundred of lines.
The code below is how I read XML from files and it appears to be a pretty standard way to read in XML files in Go.
xmlFile, err := os.Open(file)
if err != nil {
fmt.Println("Error attempting to open file: ", err)
return
}
defer xmlFile.Close()
var schema xmlschema.TFP
// Read in the bytes
byteValue, err := ioutil.ReadAll(xmlFile)
if err != nil {
fmt.Println(err)
return
}
// Read in the data into the structure
err = xml.Unmarshal(byteValue, &schema)
if err != nil {
fmt.Println(err)
return
}
Of course, given that I'm new to Go, maybe this isn't the best way to read in XML files.
Is there a way to have Go's xml/encoding library display more details on why it wasn't able to unmarshal the file? If not, what would be 3rd party alternatives?
Solution 1:[1]
From what I have seen working with go and xml, there is not a way to get more debug info logged out from any errors that the xml.Unmarshal() method returns.
I am not sure what error you are seeing, but remember that the go library is built to support XML version 1.0 only. Also: https://pkg.go.dev/encoding/xml#pkg-note-BUG
Unfortunately go's support for xml parsing is not super great compared to json support. I would suggest trying to get your input data formatted in something like json if possible to avoid a lot of headache. The third-party package support for xml parsing is also lacking.
I have seen things like https://github.com/beevik/etree that might interest you. There is little active development on XML parsers for Go though...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DirtySocrates |
