2

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

4

1 回答 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}
于 2013-04-17T19:04:45.853 回答