From 9f9d66d3b66d1d23fd5578f30b2fa084e4f83902 Mon Sep 17 00:00:00 2001 From: Roger Peppe Date: Fri, 6 Mar 2015 11:32:42 +0000 Subject: [PATCH] encoding/xml: fix default namespace of tags The struct XMLName sets the default namespace, but that's not good enough for nested tags, because an earlier tag can set the implicit parents of a subsequent tag. This change makes sure that we always explicitly set the namespace on a tag when possible. See https://go-review.googlesource.com/#/c/5910/4/src/encoding/xml/marshal_test.go@628 for discussion. Change-Id: If1afc536471c0be83e5dd80381b598476ea3f44d Reviewed-on: https://go-review.googlesource.com/6927 Reviewed-by: Nigel Tao Reviewed-by: Dave Cheney --- src/encoding/xml/marshal_test.go | 2 ++ src/encoding/xml/typeinfo.go | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/src/encoding/xml/marshal_test.go b/src/encoding/xml/marshal_test.go index 601bb30d038..8362421db74 100644 --- a/src/encoding/xml/marshal_test.go +++ b/src/encoding/xml/marshal_test.go @@ -640,6 +640,8 @@ var marshalTests = []struct { `` + `c1` + `d1` + + `` + + `` + `e1` + `` + ``, diff --git a/src/encoding/xml/typeinfo.go b/src/encoding/xml/typeinfo.go index 22248d20a6d..c9a6421f280 100644 --- a/src/encoding/xml/typeinfo.go +++ b/src/encoding/xml/typeinfo.go @@ -194,6 +194,14 @@ func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, erro return finfo, nil } + if finfo.xmlns == "" && finfo.flags&fAttr == 0 { + // If it's an element no namespace specified, get the default + // from the XMLName of enclosing struct if possible. + if xmlname := lookupXMLName(typ); xmlname != nil { + finfo.xmlns = xmlname.xmlns + } + } + // Prepare field name and parents. parents := strings.Split(tag, ">") if parents[0] == "" {