I am trying to parse an XML file and I am new to Go. I have the file below and I want to store the name and value of config
tag as a key value pair and I am stuck.
The XML file:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<TestFramework>
<config>
<name>TEST_COMPONENT</name>
<value>STORAGE</value>
<description>
Name of the test component.
</description>
</config>
<config>
<name>TEST_SUIT</name>
<value>STORAGEVOLUME</value>
<description>
Name of the test suit.
</description>
</config>
</TestFramework>
</root>
This what I have tried:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type StructFramework struct{
Configs []Config `"xml:config"`
}
type Config struct{
Name string
Value string
}
func main(){
xmlFile, err := os.Open("config.xml")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened config.xml")
// defer the closing of our xmlFile so that we can parse it later on
defer xmlFile.Close()
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(xmlFile)
var q StructFramework
xml.Unmarshal(byteValue, &q)
fmt.Println(q.Config.Name)
}
You need to improve your xml struct tags, it's kind a tricky for newcomers how to parse xml
, here is an example:
package main
import (
"encoding/xml"
"fmt"
)
type StructFramework struct {
Configs []Config `xml:"TestFramework>config"`
}
type Config struct {
Name string `xml:"name"`
Value string `xml:"value"`
}
func main() {
xmlFile := `<?xml version="1.0" encoding="UTF-8"?>
<root>
<TestFramework>
<config>
<name>TEST_COMPONENT</name>
<value>STORAGE</value>
<description>
Name of the test component.
</description>
</config>
<config>
<name>TEST_SUIT</name>
<value>STORAGEVOLUME</value>
<description>
Name of the test suit.
</description>
</config>
</TestFramework>
</root>`
var q StructFramework
xml.Unmarshal([]byte(xmlFile), &q)
fmt.Printf("%+v", q)
}
Output:
=> {Configs:[{Name:TEST_COMPONENT Value:STORAGE} {Name:TEST_SUIT Value:STORAGEVOLUME}]}