Skip to content

Commit

Permalink
Part 1 of Issue #37 and fix indexing error
Browse files Browse the repository at this point in the history
  • Loading branch information
Charles Banning committed Feb 9, 2017
1 parent 4f533f7 commit 6e78033
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
18 changes: 16 additions & 2 deletions keyvalues.go
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,20 @@ func hasSubKeys(v interface{}, subkeys map[string]interface{}) bool {
return false
}

// Per: https://github.com/clbanning/mxj/issues/37#issuecomment-278651862
var subkeySep string = ":"

func SetSubkeyFieldSeparator(s ...string) {
switch {
case len(s) == 0:
subkeySep = ":" // the default
case s[0] == "":
subkeySep = ":" // the default
default:
subkeySep = s[0]
}
}

// Generate map of key:value entries as map[string]string.
// 'kv' arguments are "name:value" pairs: attribute keys are designated with prepended hyphen, '-'.
// If len(kv) == 0, the return is (nil, nil).
Expand All @@ -499,12 +513,12 @@ func getSubKeyMap(kv ...string) (map[string]interface{}, error) {
}
m := make(map[string]interface{}, 0)
for _, v := range kv {
vv := strings.Split(v, ":")
vv := strings.Split(v, subkeySep)
switch len(vv) {
case 2:
m[vv[0]] = interface{}(vv[1])
case 3:
switch vv[3] {
switch vv[2] {
case "string", "char", "text":
m[vv[0]] = interface{}(vv[1])
case "bool", "boolean":
Expand Down
47 changes: 47 additions & 0 deletions keyvalues2_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package mxj

import (
"fmt"
"testing"
)

func TestSetSubkeyFieldSeparator(t *testing.T) {
PrependAttrWithHyphen(true)

fmt.Println("----------- TestSetSubkeyFieldSeparator")
data := `
<doc>
<elem attr="1">value 1</elem>
<elem attr="2">value 2</elem>
<elem attr="3">value 3</elem>
</doc>`

m, err := NewMapXml([]byte(data))
if err != nil {
t.Fatal(err)
}
vals, err := m.ValuesForKey("elem", "-attr:2:text")
if err != nil {
t.Fatal(err)
}
if len(vals) != 1 {
t.Fatal(":len(vals);", len(vals), vals)
}
if vals[0].(map[string]interface{})["#text"].(string) != "value 2" {
t.Fatal(":expecting: value 2; got:", vals[0].(map[string]interface{})["#text"])
}

SetSubkeyFieldSeparator("|")
defer SetSubkeyFieldSeparator()
vals, err = m.ValuesForKey("elem", "-attr|2|text")
if err != nil {
t.Fatal(err)
}
if len(vals) != 1 {
t.Fatal("|len(vals);", len(vals), vals)
}
if vals[0].(map[string]interface{})["#text"].(string) != "value 2" {
t.Fatal("|expecting: value 2; got:", vals[0].(map[string]interface{})["#text"])
}
}

0 comments on commit 6e78033

Please sign in to comment.