forked from clbanning/mxj
/
bom.go
58 lines (48 loc) · 1.13 KB
/
bom.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// from: https://www.reddit.com/r/golang/comments/99lnxd/help_needed_encodingxml_parsing_malformed_xml/
//
package main
import (
"encoding/xml"
"fmt"
"github.com/clbanning/mxj"
)
func main() {
type decodedXml struct {
XMLName xml.Name `xml:"tag" binding:"required"`
SomeAttr string `xml:"someattr,attr"`
}
data := []byte(`
-==sddsfdqsdqsdsqd
A BUNCH OF INVALID DATA IN THE XML FILE HAHAH
--SEPARATERUFCIFHEIR
Content-Type: text/plain
<tag someattr="myvalue"></tag>
--SEPARATERUFCIFHEIR--
{"hello": "world"}
`)
// don't prepend attributes with '-'
mxj.SetAttrPrefix("")
// parse the data as a map[string]interface{} value
m, err := mxj.NewMapXml(data)
if err != nil {
fmt.Println("err:", err)
return
}
// check that we got a 'tag' tagged doc
if _, ok := m["tag"]; !ok {
fmt.Println("no tag doc ...")
return
}
fmt.Printf("%v\n", m)
// extract the attribute value
attrval, err := m.ValueForPath("tag.someattr")
if err != nil {
fmt.Println("err:", err)
return
}
// create decodeXml value
val := decodedXml{
XMLName: xml.Name{"", "tag"},
SomeAttr: attrval.(string)}
fmt.Printf("%v\n", val)
}