Skip to content

Commit

Permalink
handle error conditions in Xml() and XmlIndent()
Browse files Browse the repository at this point in the history
attrprefix_test use case resulted in encoding invalid XML key and
showed that mapToXmlIndent() was not properly handling errors on
recursion.
  • Loading branch information
Charles Banning committed Nov 30, 2016
1 parent be8d58a commit 59eab4e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
8 changes: 4 additions & 4 deletions attrprefix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,11 @@ func TestMarshalPrefixNoHyphen(t *testing.T) {
if err != nil {
t.Fatal(err)
}
x, err := m.XmlIndent("", " ")
if err != nil {
t.Fatal(err)
_, err = m.XmlIndent("", " ")
if err == nil {
t.Fatal("error not reported for invalid key label")
}
fmt.Println(string(x))
fmt.Println("err ok:", err)
}

func TestMarshalPrefixUnderscore(t *testing.T) {
Expand Down
19 changes: 15 additions & 4 deletions xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ func mapToXmlIndent(doIndent bool, s *string, key string, value interface{}, pp
var n int
var ss string
for k, v := range vv {
if k[:lenAttrPrefix] == attrPrefix {
if lenAttrPrefix > 0 && lenAttrPrefix < len(k) && k[:lenAttrPrefix] == attrPrefix {
switch v.(type) {
case string:
if xmlEscapeChars {
Expand Down Expand Up @@ -833,7 +833,14 @@ func mapToXmlIndent(doIndent bool, s *string, key string, value interface{}, pp
elen = 1
isSimple = true
break
} else if ok {
// Handle edge case where simple element with attributes
// is unmarshal'd using NewMapXml() where attribute prefix
// has been set to "".
// TODO(clb): should probably scan all keys for invalid chars.
return fmt.Errorf("invalid attribute key label: #text - due to attributes not being prefixed")
}

// close tag with possible attributes
*s += ">"
if doIndent {
Expand All @@ -845,7 +852,7 @@ func mapToXmlIndent(doIndent bool, s *string, key string, value interface{}, pp
elemlist := make([][2]interface{}, len(vv))
n = 0
for k, v := range vv {
if k[:lenAttrPrefix] == attrPrefix {
if lenAttrPrefix > 0 && lenAttrPrefix < len(k) && k[:lenAttrPrefix] == attrPrefix {
continue
}
elemlist[n][0] = k
Expand All @@ -864,7 +871,9 @@ func mapToXmlIndent(doIndent bool, s *string, key string, value interface{}, pp
}
}
i++
mapToXmlIndent(doIndent, s, v[0].(string), v[1], p)
if err := mapToXmlIndent(doIndent, s, v[0].(string), v[1], p); err != nil {
return err
}
switch v[1].(type) {
case []interface{}: // handled in []interface{} case
default:
Expand Down Expand Up @@ -892,7 +901,9 @@ func mapToXmlIndent(doIndent bool, s *string, key string, value interface{}, pp
if doIndent {
p.Indent()
}
mapToXmlIndent(doIndent, s, key, v, p)
if err := mapToXmlIndent(doIndent, s, key, v, p); err != nil {
return err
}
if doIndent {
p.Outdent()
}
Expand Down

0 comments on commit 59eab4e

Please sign in to comment.