Commit ca3e6d13 authored by Gustavo Niemeyer's avatar Gustavo Niemeyer

encoding/xml: marshal/unmarshal xml.Name in field

R=rsc
CC=golang-dev
https://golang.org/cl/5542052
parent fec7aa95
...@@ -150,6 +150,10 @@ type XMLNameWithoutTag struct { ...@@ -150,6 +150,10 @@ type XMLNameWithoutTag struct {
Value string ",chardata" Value string ",chardata"
} }
type NameInField struct {
Foo Name `xml:"ns foo"`
}
type AttrTest struct { type AttrTest struct {
Int int `xml:",attr"` Int int `xml:",attr"`
Lower int `xml:"int,attr"` Lower int `xml:"int,attr"`
...@@ -483,6 +487,19 @@ var marshalTests = []struct { ...@@ -483,6 +487,19 @@ var marshalTests = []struct {
UnmarshalOnly: true, UnmarshalOnly: true,
}, },
// xml.Name works in a plain field as well.
{
Value: &NameInField{Name{Space: "ns", Local: "foo"}},
ExpectXML: `<NameInField><foo xmlns="ns"></foo></NameInField>`,
},
// Marshaling zero xml.Name uses the tag or field name.
{
Value: &NameInField{},
ExpectXML: `<NameInField><foo xmlns="ns"></foo></NameInField>`,
MarshalOnly: true,
},
// Test attributes // Test attributes
{ {
Value: &AttrTest{ Value: &AttrTest{
......
...@@ -271,6 +271,10 @@ func (p *Parser) unmarshal(val reflect.Value, start *StartElement) error { ...@@ -271,6 +271,10 @@ func (p *Parser) unmarshal(val reflect.Value, start *StartElement) error {
case reflect.Struct: case reflect.Struct:
sv = v sv = v
typ := sv.Type() typ := sv.Type()
if typ == nameType {
v.Set(reflect.ValueOf(start.Name))
break
}
tinfo, err = getTypeInfo(typ) tinfo, err = getTypeInfo(typ)
if err != nil { if err != nil {
return err return err
......
...@@ -46,6 +46,8 @@ const ( ...@@ -46,6 +46,8 @@ const (
var tinfoMap = make(map[reflect.Type]*typeInfo) var tinfoMap = make(map[reflect.Type]*typeInfo)
var tinfoLock sync.RWMutex var tinfoLock sync.RWMutex
var nameType = reflect.TypeOf(Name{})
// getTypeInfo returns the typeInfo structure with details necessary // getTypeInfo returns the typeInfo structure with details necessary
// for marshalling and unmarshalling typ. // for marshalling and unmarshalling typ.
func getTypeInfo(typ reflect.Type) (*typeInfo, error) { func getTypeInfo(typ reflect.Type) (*typeInfo, error) {
...@@ -56,7 +58,7 @@ func getTypeInfo(typ reflect.Type) (*typeInfo, error) { ...@@ -56,7 +58,7 @@ func getTypeInfo(typ reflect.Type) (*typeInfo, error) {
return tinfo, nil return tinfo, nil
} }
tinfo = &typeInfo{} tinfo = &typeInfo{}
if typ.Kind() == reflect.Struct { if typ.Kind() == reflect.Struct && typ != nameType {
n := typ.NumField() n := typ.NumField()
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
f := typ.Field(i) f := typ.Field(i)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment