Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions src/encoding/xml/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,15 @@ func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplat

// marshalAttr marshals an attribute with the given name and value, adding to start.Attr.
func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) error {
// Dereference or skip nil pointer, interface values.
switch val.Kind() {
case reflect.Pointer, reflect.Interface:
if val.IsNil() {
return nil
}
val = val.Elem()
}

if val.CanInterface() && val.Type().Implements(marshalerAttrType) {
attr, err := val.Interface().(MarshalerAttr).MarshalXMLAttr(name)
if err != nil {
Expand Down Expand Up @@ -601,15 +610,6 @@ func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value)
}
}

// Dereference or skip nil pointer, interface values.
switch val.Kind() {
case reflect.Pointer, reflect.Interface:
if val.IsNil() {
return nil
}
val = val.Elem()
}

// Walk slices.
if val.Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
n := val.Len()
Expand Down
9 changes: 9 additions & 0 deletions src/encoding/xml/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ type MarshalerStruct struct {
Foo MyMarshalerAttrTest `xml:",attr"`
}

type IMarshalerStruct struct {
Foo interface{} `xml:",attr"`
}

type InnerStruct struct {
XMLName Name `xml:"testns outer"`
}
Expand Down Expand Up @@ -1252,6 +1256,11 @@ var marshalTests = []struct {
ExpectXML: `<MarshalerStruct Foo="hello world"></MarshalerStruct>`,
Value: &MarshalerStruct{},
},
{
ExpectXML: `<IMarshalerStruct Foo="hello world"></IMarshalerStruct>`,
Value: &IMarshalerStruct{Foo: &MyMarshalerAttrTest{}},
MarshalOnly: true,
},
{
ExpectXML: `<outer xmlns="testns" int="10"></outer>`,
Value: &OuterStruct{IntAttr: 10},
Expand Down