英文:
Unmarshalling XML attributes into a named, nested struct
问题
从当前的XML元素中解组属性到一个匿名结构体中是可行的:
package main
import (
"encoding/xml"
"fmt"
)
type Attrs struct {
Attr1 int `xml:"attr1,attr"`
Attr2 int `xml:"attr2,attr"`
}
type Element struct {
Attrs
}
func main() {
data := `<element attr1="1" attr2="2"></element>`
v := Element{}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%#v\n", v)
}
这将按预期打印出 main.Element{Attrs:main.Attrs{Attr1:1, Attr2:2}}
。
如果给匿名结构体成员命名,v.Attr1
和 v.Attr2
将无法解组。
type Element struct {
AttrGroup Attrs
}
在这种情况下,应该使用什么正确的标签?
英文:
Unmarshalling attributes from the current XML element into an anonymous struct works:
package main
import (
"encoding/xml"
"fmt"
)
type Attrs struct {
Attr1 int `xml:"attr1,attr"`
Attr2 int `xml:"attr2,attr"`
}
type Element struct {
Attrs
}
func main() {
data := `<element attr1="1" attr2="2"></element>`
v := Element{}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%#v\n", v)
}
This prints main.Element{Attrs:main.Attrs{Attr1:1, Attr2:2}}
as expected.
If the anonymous struct member is given a name, v.Attr1
and v.Attr2
are not unmarshalled.
type Element struct {
AttrGroup Attrs
}
What's the correct tag to use on the struct member in this case?
Edit: Playground version
答案1
得分: 1
为什么不直接这样做呢?我不明白命名的结构体除了复杂性之外还能带来什么好处。
package main
import (
"encoding/xml"
"fmt"
)
type Element struct {
Attr1 int `xml:"attr1,attr"`
Attr2 int `xml:"attr2,attr"`
}
func main() {
data := `<element attr1="1" attr2="2"></element>`
v := Element{}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%#v\n", v)
}
输出结果为
main.Element{Attr1:1, Attr2:2}
英文:
Why not just do this? I don't see what the named struct buys you other than complexity.
package main
import (
"encoding/xml"
"fmt"
)
type Element struct {
Attr1 int `xml:"attr1,attr"`
Attr2 int `xml:"attr2,attr"`
}
func main() {
data := `<element attr1="1" attr2="2"></element>`
v := Element{}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("%#v\n", v)
}
Which prints
main.Element{Attr1:1, Attr2:2}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论