Skip to content

Commit

Permalink
Allow override for decoding simple element w/o attributes
Browse files Browse the repository at this point in the history
It was an easy change to decode all simple elements values as map["#text":<value>] event if they do not have attributes.
  • Loading branch information
clbanning committed Jan 21, 2019
1 parent e2562de commit b0d71e6
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
19 changes: 18 additions & 1 deletion xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,23 @@ func HandleXMPPStreamTag(b ...bool) {
}
}

// 21jan18 - decode all values as map["#text":value] (issue #56)
var decodeSimpleValuesAsMap bool

// DecodeSimpleValuesAsMap forces all values to be decoded as map["#text":<value>].
// If called with no argument, the decoding is toggled on/off.
//
// By default the NewMapXml functions decode simple values without attributes as
// map[<tag>:<value>]. This function causes simple values without attributes to be
// decoded the same as simple values with attributes - map[<tag>:map["#text":<value>]].
func DecodeSimpleValuesAsMap(b ...bool) {
if len(b) == 0 {
decodeSimpleValuesAsMap = !decodeSimpleValuesAsMap
} else if len(b) == 1 {
decodeSimpleValuesAsMap = b[0]
}
}

// xmlToMapParser (2015.11.12) - load a 'clean' XML doc into a map[string]interface{} directly.
// A refactoring of xmlToTreeParser(), markDuplicate() and treeToMap() - here, all-in-one.
// We've removed the intermediate *node tree with the allocation and subsequent rescanning.
Expand Down Expand Up @@ -419,7 +436,7 @@ func xmlToMapParser(skey string, a []xml.Attr, p *xml.Decoder, r bool) (map[stri
// clean up possible noise
tt := strings.Trim(string(t.(xml.CharData)), "\t\r\b\n ")
if len(tt) > 0 {
if len(na) > 0 {
if len(na) > 0 || decodeSimpleValuesAsMap {
na["#text"] = cast(tt, r)
} else if skey != "" {
n[skey] = cast(tt, r)
Expand Down
25 changes: 25 additions & 0 deletions xml3_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,28 @@ func TestOnlyAttributesSeq(t *testing.T) {
}
fmt.Println(string(xml))
}

func TestDecodeSimpleValuesAsMap(t *testing.T) {
fmt.Println("========== TestDecodeSimpleValuesAsMap")
DecodeSimpleValuesAsMap()

xml := `<item>
<id>30102</id>
<title>Mini Drone Inteligente - Branco</title>
<price unit="BRL">149.90</price>
</item>`
m, err := NewMapXml([]byte(xml))
if err != nil {
t.Fatal(err)
}
fmt.Println("xml:", string(xml))
fmt.Printf("m : %v\n", m)

fmt.Println("========== (default)")
DecodeSimpleValuesAsMap()
m, err = NewMapXml([]byte(xml))
if err != nil {
t.Fatal(err)
}
fmt.Printf("m : %v\n", m)
}

0 comments on commit b0d71e6

Please sign in to comment.