Skip to content

Commit

Permalink
feat: add extract existing attributes in map and unit test (#7)
Browse files Browse the repository at this point in the history
* feat: add extract existing attributes in map and unit test

* fix: duplicate code

---------

Co-authored-by: jianchao.ma <[email protected]>
Co-authored-by: Youen Péron <[email protected]>
  • Loading branch information
3 people authored Nov 8, 2023
1 parent 5492b91 commit 2c1872a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pkg/xixo/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ func XMLElementToMapCallback(callback CallbackMap) Callback {
dict[name] = child[0].InnerText
}

extractExistedAttributes(xmlElement, dict)

dict, err := callback(dict)
if err != nil {
return nil, err
Expand Down Expand Up @@ -60,6 +62,18 @@ func XMLElementToMapCallback(callback CallbackMap) Callback {
return result
}

func extractExistedAttributes(xmlElement *XMLElement, dict map[string]string) {
for name, child := range xmlElement.Childs {
for attr, value := range child[0].Attrs {
dict[name+"@"+attr] = value
}
}

for attr, value := range xmlElement.Attrs {
dict["@"+attr] = value
}
}

// extractChildAttributes extracts child attributes from the dictionary.
func extractChildAttributes(dict map[string]string) map[string][]Attribute {
childAttributes := make(map[string][]Attribute)
Expand Down
32 changes: 32 additions & 0 deletions pkg/xixo/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,35 @@ func TestModifyAttributsWithMapCallback(t *testing.T) {
t.Errorf("Le résultat XML ne correspond pas à l'attendu.\nAttendu:\n%s\nObtenu:\n%s", expectedResultXML, resultXML)
}
}

func TestAttributsWithMapCallbackIsInDictionary(t *testing.T) {
t.Parallel()
// Fichier XML en entrée
inputXML := `
<root type="foo">
<element1 age="22" sex="male">Hello world!</element1>
<element2>Contenu2 !</element2>
</root>`

// Lisez les résultats du canal et construisez le XML résultant
var resultXMLBuffer bytes.Buffer

// Créez un bufio.Reader à partir du XML en entrée
reader := bytes.NewBufferString(inputXML)

// Créez une nouvelle instance du parser XML avec la fonction de rappel
parser := xixo.NewXMLParser(reader, &resultXMLBuffer).EnableXpath()
parser.RegisterMapCallback("root", func(m map[string]string) (map[string]string, error) {
assert.Equal(t, m["@type"], "foo")
assert.Equal(t, m["element1@age"], "22")
assert.Equal(t, m["element1@sex"], "male")
assert.Equal(t, m["element1"], "Hello world!")
assert.Equal(t, m["element2"], "Contenu2 !")

return m, nil
})

// Créez un canal pour collecter les résultats du parser
err := parser.Stream()
assert.Nil(t, err)
}

0 comments on commit 2c1872a

Please sign in to comment.