我是 Go 新手,我正在尝试解析 XML 文件。我的目标是通过只为所有配置标签创建一种结构来获取它们的值。每个父标签不是一个单独的结构。下面是 XML 文件以及我所做的事情。
我的 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<TestFramework>
<config>
<name>TEST_COMPONENT</name>
<value>FILMS</value>
<description>
Name of the test Films.
</description>
</config>
<config>
<name>TESTER_NAME</name>
<value><a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2939091b28a8b88dc919d9f" rel="noreferrer noopener nofollow">[email protected]</a></value>
<description>
Name or email of the tester.
</description>
</config>
</TestFramework>
<Product>
<config>
<name>PRODUCT_RELEASE</name>
<value>2.1</value>
<description>
Name or email of the tester.
</description>
</config>
<config>
<name>PRODUCT_BUILD</name>
<value>7.1.3182018</value>
<description>
Name or email of the tester.
</description>
</config>
</Product>
</root>
我的Go程序:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type ConfigFile struct {
Configs []Config `xml:"config"`
}
type Config struct {
Name string `xml:"name"`
Value string `xml:"value"`
}
func main() {
xmlFile, err := os.Open("octa_config.xml")
m := make(map[string]string)
if err != nil {
fmt.Println(err)
}else {
fmt.Println("Successfully Opened octa_config.xml")
}
defer xmlFile.Close()
byteValue, _ := ioutil.ReadAll(xmlFile)
var c ConfigFile
xml.Unmarshal(byteValue,&c)
for i := 0; i < len(c.Configs); i++ {
m[c.Configs[i].Name]=c.Configs[i].Value
}
for k,v :=range m{
fmt.Println( k,v)
}
}
我知道我可以制作这样的结构:
type TestFramework struct {
Configs []Config `xml:"TestFramework>config"`
}
但我不想使用这个:
`xml:"TestFramework>config"`
我得到这样的输出:
D:\Go>go run config_nim.go
Successfully Opened octa_config.xml
D:\Go>
最佳答案
您可以使用 ,any
标记选项。
type root struct {
XMLName xml.Name `xml:"root"`
Files []ConfigFile `xml:",any"`
}
type ConfigFile struct {
Configs []Config `xml:"config"`
}
type Config struct {
Name string `xml:"name"`
Value string `xml:"value"`
Description string `xml:"description"`
}
关于Go中不同父标签下相同标签的XML解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52492893/