forked from FooSoft/jmdict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
51 lines (43 loc) · 1.05 KB
/
common.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
package jmdict
import (
"encoding/xml"
"io"
"regexp"
)
func parseDict(reader io.Reader, container interface{}, transform bool) (map[string]string, error) {
decoder := xml.NewDecoder(reader)
var entities map[string]string
for {
token, _ := decoder.Token()
if token == nil {
break
}
switch startElement := token.(type) {
case xml.Directive:
directive := token.(xml.Directive)
entities = parseEntities(&directive)
if transform {
decoder.Entity = entities
} else {
decoder.Entity = make(map[string]string)
for k, _ := range entities {
decoder.Entity[k] = k
}
}
case xml.StartElement:
if err := decoder.DecodeElement(container, &startElement); err != nil {
return nil, err
}
}
}
return entities, nil
}
func parseEntities(d *xml.Directive) map[string]string {
re := regexp.MustCompile("<!ENTITY\\s([0-9\\-A-z]+)\\s\"(.+)\">")
matches := re.FindAllStringSubmatch(string(*d), -1)
entities := make(map[string]string)
for _, match := range matches {
entities[match[1]] = match[2]
}
return entities
}