-
Notifications
You must be signed in to change notification settings - Fork 0
/
xml_parser.go
44 lines (35 loc) · 921 Bytes
/
xml_parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package st2
import (
"bytes"
xj "github.com/basgys/goxml2json"
)
type XMLUnmarshalTagFormat struct {
ContentTagPrefix string
AttributeTagPrefix string
}
func (x XMLUnmarshalTagFormat) Unmarshal(data []byte, v any) error {
reader := bytes.NewReader(data)
root := &xj.Node{}
decoder := xj.NewDecoder(reader)
err := decoder.DecodeWithCustomPrefixes(root, x.ContentTagPrefix, x.AttributeTagPrefix)
if err != nil {
return err
}
buf := new(bytes.Buffer)
encoder := xj.NewEncoder(buf)
err = encoder.Encode(root)
if err != nil {
return err
}
json := buf.Bytes()
return jsonapi.Unmarshal(json, v)
}
func (x XMLUnmarshalTagFormat) TagFormat() string {
return `xml:"%s"`
}
func NewXMLParser(ctx Context) *StructuredParser {
return NewStructuredParser(ctx, &XMLUnmarshalTagFormat{
ContentTagPrefix: ctx.XMLContext.ContentTagPrefix,
AttributeTagPrefix: ctx.XMLContext.AttributeTagPrefix,
})
}