I am new to Go and I am trying to validate XML, but I am not able to do it. Below is what I have tried but it's not working. Is there any way to do it.
func ParseXml(xml_path string) {
xmlFile, err := os.Open(xml_path)
if err != nil {
panic(err)
}
// defer the closing of our xmlFile so that we can parse it later on
defer xmlFile.Close()
// read our opened xmlFile1 as a byte array. here I am checking if the file is valid or not
byteValue, err := ioutil.ReadAll(xmlFile)
if err != nil {
panic(fmt.Sprintf("%s file reading failed
",xml_path))
}
}
Although I am passing an invalid XML file, but I am not getting panic after
byteValue, err := ioutil.ReadAll(xmlFile)
Your code doesn't validate XML syntax. Your code reads a file regardless of what it does. Easiest way to validate XML is with the xml
package.
func IsValidXML(data []byte) bool {
return xml.Unmarshal(data, new(interface{})) != nil
}
So regarding your code, it should become like so :
func ParseXml(xml_path string) {
xmlFile, err := os.Open(xml_path)
if err != nil {
panic(err)
}
// defer the closing of our xmlFile so that we can parse it later on
defer xmlFile.Close()
// read our opened xmlFile1 as a byte array. here I am checking if the file is valid or not
byteValue, err := ioutil.ReadAll(xmlFile)
if err != nil {
panic(fmt.Sprintf("%s file reading failed
",xml_path))
}
if !IsValidXML(byteValue) {
panic("Invalid XML has been input")
}
}
For documentation of xml.Unmarshal
, visit https://golang.org/pkg/encoding/xml/#Unmarshal