gpt4 book ai didi

xml - 如何进行 XML 解析?

转载 作者:IT王子 更新时间:2023-10-29 01:56:49 25 4
gpt4 key购买 nike

我正在尝试解析一个 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结构标签,对于新手来说如何解析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}]}

关于xml - 如何进行 XML 解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52442228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com