【问题标题】:How to do XML parsing?如何进行 XML 解析?
【发布时间】:2019-08-07 19:07:09
【问题描述】:

我正在尝试解析 XML 文件,但我是 Go 新手。我有下面的文件,我想将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)
}

【问题讨论】:

    标签: xml go xml-parsing


    【解决方案1】:

    你需要改进你的xml结构标签,对于新手来说如何解析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}]}
    

    【讨论】:

    • 谢谢,它成功了。但是你能解释一下什么是“%+v”
    • 阅读fmt的文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2013-07-18
    • 2011-10-20
    • 1970-01-01
    • 2019-09-27
    相关资源
    最近更新 更多