Skip to content

Commit

Permalink
Merge pull request #6 from eloyucu/master
Browse files Browse the repository at this point in the history
Add a function to get the value of a field by path and indexation.
  • Loading branch information
tamerh authored Jul 29, 2019
2 parents 0a17748 + 7098928 commit 763cb39
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
18 changes: 18 additions & 0 deletions xmlparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,24 @@ func (x *XMLParser) Stream() chan *XMLElement {

}

func (element *XMLElement) GetValue(paths []string, indexes []int, attr string) string {
if len(indexes) == 0 {
indexes = make([]int, len(paths))
}
path, paths := paths[0], paths[1:]
index, indexes := indexes[0], indexes[1:]
if len(element.Childs[path]) > 0 {
if len(paths) == 0 {
if attr == "" {
return element.Childs[path][index].InnerText
}
return element.Childs[path][index].Attrs[attr]
}
return element.Childs[path][index].GetValue(paths, indexes, attr)
}
return ""
}

func (x *XMLParser) parse() {

defer close(x.resultChannel)
Expand Down
32 changes: 32 additions & 0 deletions xmlparser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,38 @@ func TestError(t *testing.T) {

}

func TestGetField(t *testing.T) {
var found string
p := getparser("examples")
for xml := range p.Stream() {
found = xml.GetValue([]string{"tag1", "tag11"}, []int{}, "")
if found != "InnerText110" {
t.Errorf("tag1>tag11 doesn´t match with expected \n\t Expected: %s \n\t Found: %s", "InnerText110", found)
}
found = xml.GetValue([]string{"tag1", "tag11"}, []int{0, 1}, "")
if found != "InnerText111" {
t.Errorf("tag1>tag11 doesn´t match with expected \n\t Expected: %s \n\t Found: %s", "InnerText111", found)
}
found = xml.GetValue([]string{"tag1", "tag11"}, []int{1, 0}, "")
if found != "InnerText2" {
t.Errorf("tag1>tag11 doesn´t match with expected \n\t Expected: %s \n\t Found: %s", "InnerText2", found)
}
found = xml.GetValue([]string{"tag1", "tag12"}, []int{1, 0}, "att1")
if found != "att1" {
t.Errorf("tag1>tag12>@att1 doesn´t match with expected \n\t Expected: %s \n\t Found: %s", "att1", found)
}
found = xml.GetValue([]string{"missingtag", "tag12", "tag13"}, []int{0, 0, 0}, "")
if found != "" {
t.Errorf("missingtag>tag12>tag13 doesn´t match with expected \n\t Expected: %s \n\t Found: %s", "att1", found)
}
found = xml.GetValue([]string{"tag1", "tag12", "missingtag"}, []int{1, 0, 0}, "att1")
if found != "" {
t.Errorf("tag1>tag12>missingtag>@att1 doesn´t match with expected \n\t Expected: %s \n\t Found: %s", "att1", found)
}
}

}

func Benchmark1(b *testing.B) {

for n := 0; n < b.N; n++ {
Expand Down

0 comments on commit 763cb39

Please sign in to comment.