Skip to content

Commit

Permalink
Encode arbitrary struct values
Browse files Browse the repository at this point in the history
  • Loading branch information
clbanning committed Dec 9, 2020
1 parent 1d3f659 commit 8ff6af5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
27 changes: 27 additions & 0 deletions structvalue_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package mxj

import (
"encoding/xml"
"fmt"
"testing"
)

type result struct {
XMLName xml.Name `xml:"xml"`
Content string `xml:"content"`
}

func TestStructValue(t *testing.T) {
fmt.Println("----------------- structvalue_test.go ...")

data, err := Map(map[string]interface{}{
"data": result{Content: "content"},
}).Xml()
if err != nil {
t.Fatal(err)
}

if string(data) != "<data><xml><content>content</content></xml></data>" {
t.Fatal("encoding error:", string(data))
}
}
14 changes: 11 additions & 3 deletions xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -969,8 +969,17 @@ func marshalMapToXmlIndent(doIndent bool, b *bytes.Buffer, key string, value int
case []map[string]interface{}, []string, []float64, []bool, []int, []int32, []int64, []float32, []json.Number:
case []interface{}:
default:
// coerce eveything else into a string value
value = fmt.Sprint(value)
// see if value is a struct, if so marshal using encoding/xml package
if reflect.ValueOf(value).Kind() == reflect.Struct {
if v, err := xml.Marshal(value); err != nil {
return err
} else {
value = string(v)
}
} else {
// coerce eveything else into a string value
value = fmt.Sprint(value)
}
}

// start the XML tag with required indentaton and padding
Expand Down Expand Up @@ -1322,4 +1331,3 @@ func (e elemList) Swap(i, j int) {
func (e elemList) Less(i, j int) bool {
return e[i][0].(string) <= e[j][0].(string)
}

0 comments on commit 8ff6af5

Please sign in to comment.