Golang XML解析如何做?

时间:2018-09-21 10:56:25

标签: xml go xml-parsing

您好,我尝试解析XML文件,但我对golang并不陌生。我在下面的文件中,我想将config标签的名称和值存储为键值对,并且卡在其中。谁能帮忙。

下面是XML文件。

<?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>

现在这是我尝试过的。

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)
}

1 个答案:

答案 0 :(得分:3)

您需要改进xml struct标签,对于新手来说,解析xml有点棘手,下面是一个示例:

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)
}

Playground

输出:

=> {Configs:[{Name:TEST_COMPONENT Value:STORAGE} {Name:TEST_SUIT Value:STORAGEVOLUME}]}