]> Cypherpunks repositories - gostls13.git/commitdiff
encoding/xml: marshal/unmarshal xml.Name in field
authorGustavo Niemeyer <gustavo@niemeyer.net>
Thu, 19 Jan 2012 22:15:55 +0000 (20:15 -0200)
committerGustavo Niemeyer <gustavo@niemeyer.net>
Thu, 19 Jan 2012 22:15:55 +0000 (20:15 -0200)
R=rsc
CC=golang-dev
https://golang.org/cl/5542052

src/pkg/encoding/xml/marshal_test.go
src/pkg/encoding/xml/read.go
src/pkg/encoding/xml/typeinfo.go

index bec53761e1a31ea25dedaddc01627354065e1386..f23b2cb7e080e2bc226d45ecbd789f1f65503c69 100644 (file)
@@ -150,6 +150,10 @@ type XMLNameWithoutTag struct {
        Value   string ",chardata"
 }
 
+type NameInField struct {
+       Foo Name `xml:"ns foo"`
+}
+
 type AttrTest struct {
        Int   int     `xml:",attr"`
        Lower int     `xml:"int,attr"`
@@ -483,6 +487,19 @@ var marshalTests = []struct {
                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
        {
                Value: &AttrTest{
index dde68de3e7839c35fedce20c45a5ca2ad3883c16..4419ed1e4773fc111b26a891cc10411a40cd008a 100644 (file)
@@ -271,6 +271,10 @@ func (p *Parser) unmarshal(val reflect.Value, start *StartElement) error {
        case reflect.Struct:
                sv = v
                typ := sv.Type()
+               if typ == nameType {
+                       v.Set(reflect.ValueOf(start.Name))
+                       break
+               }
                tinfo, err = getTypeInfo(typ)
                if err != nil {
                        return err
index 8f79c4e78bbb6a6f3ce7569b79e6ea20edf0942c..36b35ed2ee888920cf6ec75c68c7cc04144a21de 100644 (file)
@@ -46,6 +46,8 @@ const (
 var tinfoMap = make(map[reflect.Type]*typeInfo)
 var tinfoLock sync.RWMutex
 
+var nameType = reflect.TypeOf(Name{})
+
 // getTypeInfo returns the typeInfo structure with details necessary
 // for marshalling and unmarshalling typ.
 func getTypeInfo(typ reflect.Type) (*typeInfo, error) {
@@ -56,7 +58,7 @@ func getTypeInfo(typ reflect.Type) (*typeInfo, error) {
                return tinfo, nil
        }
        tinfo = &typeInfo{}
-       if typ.Kind() == reflect.Struct {
+       if typ.Kind() == reflect.Struct && typ != nameType {
                n := typ.NumField()
                for i := 0; i < n; i++ {
                        f := typ.Field(i)