Bra*_*ody 1 xml go xml-parsing
我必须遗漏一些非常明显的东西...我试图解析一个简单的XML文件,遵循以下示例ExampleUnmarshal():http://golang.org/src/pkg/encoding/xml/example_test.go
正如您将在底部看到的那样,没有任何属性或子元素被映射 - 无论是方向 - Marshal还是Unmarshal.从我可以看出这几乎与他们在上面的example_test.go中所做的完全相同(我可以看到的唯一区别是该测试中的类型在函数的范围内 - 我尝试过,没有差异,并且他们正在使用子元素而不是属性 - 除了id- 但是根据文档名称,attr应该工作.
代码如下所示:
package main
import (
"fmt"
"encoding/xml"
"io/ioutil"
)
type String struct {
XMLName xml.Name `xml:"STRING"`
lang string `xml:"lang,attr"`
value string `xml:"value,attr"`
}
type Entry struct {
XMLName xml.Name `xml:"ENTRY"`
id string `xml:"id,attr"`
strings []String
}
type Dictionary struct {
XMLName xml.Name `xml:"DICTIONARY"`
thetype string `xml:"type,attr"`
ignore string `xml:"ignore,attr"`
entries []Entry
}
func main() {
dict := Dictionary{}
b := []byte(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DICTIONARY type="multilanguage" ignore="en">
<ENTRY id="ActionText.Description.AI_ConfigureChainer">
<STRING lang="en" value="ActionText.Description.AI_ConfigureChainer"/>
<STRING lang="da" value=""/>
<STRING lang="nl" value=""/>
<STRING lang="fi" value=""/>
</ENTRY>
</DICTIONARY>
`)
err := xml.Unmarshal(b, &dict)
if err != nil { panic(err) }
fmt.Println(dict) // prints: {{ DICTIONARY} []}
dict.ignore = "test"
out, err := xml.MarshalIndent(&dict, " ", " ")
fmt.Println(string(out)) // prints: <DICTIONARY></DICTIONARY>
// huh?
}
Run Code Online (Sandbox Code Playgroud)
您需要导出(大写)您的结构字段.
从encoding/xml Marshall功能文档:
struct的XML元素包含struct的每个导出字段的编组元素
请参阅无法在golang中解析复杂的json以获取相关答案.