Как сделать синтаксический анализ XML? - PullRequest
0 голосов
/ 21 сентября 2018

Я пытаюсь разобрать файл 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)
}

1 Ответ

0 голосов
/ 21 сентября 2018

Вам нужно улучшить свои теги 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}]}
...