去xml解析“看不到”任何领域 [英] go xml parsing "doesn't see" any fields
问题描述
我必须错过一些非常明显的东西......我尝试解析一个简单的XML文件,按照 ExampleUnmarshal()
的例子在这里: http://golang.org/src/pkg/encoding/xml/example_test.go
I must be missing something really obvious... Am trying to parse a simple XML file, following the example from ExampleUnmarshal()
in here: http://golang.org/src/pkg/encoding/xml/example_test.go
正如您在底部看到的,没有任何属性或子元素正在映射 - 无论是方向还是元帅还是Unmarshal。从我可以告诉的这几乎是他们在上面的example_test.go中完全相同的事情(我能看到的唯一区别是那个测试中的类型在函数的范围内 - 我试过了,没有区别,他们使用子元素而不是属性 - 除了 id
- 但是每个 doc name,attr should work afaict)。
As you'll see at the bottom of this, none of the attributes or child elements are being mapped - either direction - Marshal or Unmarshal. From what I can tell this is almost the exact same thing they are doing in example_test.go above (the only differences I can see are the that types in that test are within the scope of the function - which I tried, makes no diff, and they are using child elements and not attributes - except for id
- but per doc name,attr should work afaict).
代码如下所示:
Code looks like this:
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?
}
推荐答案
导出(大写)您的结构字段。
You need to Export (Capitalize) your struct fields.
从 encoding / xml
Marshall
功能文档:
From the encoding/xml
Marshall
function docs:
结构的XML元素包含每个结构的导出字段的编组元素
The XML element for a struct contains marshalled elements for each of the exported fields of the struct
请参阅无法解析golang中复杂的json 为相关答案。
这篇关于去xml解析“看不到”任何领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!