英文:
Golang - unmarshal extra XML attributes
问题
有没有一种方法可以解析具有动态属性的XML标签(我不知道每次会得到哪些属性)。
也许目前还不支持。请参阅Issue 3633: encoding/xml: support for collecting all attributes
类似于:
package main
import (
    "encoding/xml"
    "fmt"
)
func main() {
    var v struct {
        Attributes []xml.Attr `xml:",any"`
    }
    data := `<TAG ATTR1="VALUE1" ATTR2="VALUE2" />`
    err := xml.Unmarshal([]byte(data), &v)
    if err != nil {
        panic(err)
    }
    fmt.Println(v)
}
英文:
Is there a way to unmarshal XML tags with dynamic attributes (I don't know which attributes I'll get every time).
Maybe it's not supported yet. See Issue 3633: encoding/xml: support for collecting all attributes
Something like :
package main
import (
	"encoding/xml"
	"fmt"
)
func main() {
	var v struct {
		Attributes []xml.Attr `xml:",any"`
	}
	data := `<TAG ATTR1="VALUE1" ATTR2="VALUE2" />`
	err := xml.Unmarshal([]byte(data), &v)
	if err != nil {
        panic(err)
	}
	fmt.Println(v)
}
答案1
得分: 6
截至2017年底,可以使用以下代码来支持此功能:
var v struct {
    Attributes []xml.Attr `xml:",any,attr"`
}
请参阅 https://github.com/golang/go/issues/3633
英文:
As of late 2017, this is supported by using:
var v struct {
    Attributes []xml.Attr `xml:",any,attr"`
}
Please see https://github.com/golang/go/issues/3633
答案2
得分: 4
你需要实现自己的XMLUnmarshaler。
package main
import (
	"encoding/xml"
	"fmt"
)
type CustomTag struct {
	Name       string
	Attributes []xml.Attr
}
func (c *CustomTag) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	c.Name = start.Name.Local
	c.Attributes = start.Attr
	return d.Skip()
}
func main() {
	v := &CustomTag{}
	data := []byte(`<tag ATTR1="VALUE1" ATTR2="VALUE2" />`)
	err := xml.Unmarshal(data, &v)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", v)
}
输出结果为:
&{Name:tag Attributes:[{Name:{Space: Local:ATTR1} Value:VALUE1} {Name:{Space: Local:ATTR2} Value:VALUE2}]}
这里是示例代码的链接。
英文:
You need to implement your own XMLUnmarshaler
package main
import (
	"encoding/xml"
	"fmt"
)
type CustomTag struct {
	Name       string
	Attributes []xml.Attr
}
func (c *CustomTag) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	c.Name = start.Name.Local
	c.Attributes = start.Attr
	return d.Skip()
}
func main() {
	v := &CustomTag{}
	data := []byte(`<tag ATTR1="VALUE1" ATTR2="VALUE2" />`)
	err := xml.Unmarshal(data, &v)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", v)
}
outputs
&{Name:tag Attributes:[{Name:{Space: Local:ATTR1} Value:VALUE1} {Name:{Space: Local:ATTR2} Value:VALUE2}]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论