ParseEntityMap searches for a DOCTYPE directive in the given nodes and extracts entity declarations into a map.
(nodes []Token)
| 12 | // ParseEntityMap searches for a DOCTYPE directive in the given nodes |
| 13 | // and extracts entity declarations into a map. |
| 14 | func ParseEntityMap(nodes []Token) map[string][]byte { |
| 15 | // Find doctype |
| 16 | var doctype *Directive |
| 17 | for _, node := range nodes { |
| 18 | if dir, ok := node.(*Directive); ok { |
| 19 | doctype = dir |
| 20 | break |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | if doctype == nil { |
| 25 | return nil |
| 26 | } |
| 27 | |
| 28 | start := bytes.IndexByte(doctype.Data, '[') |
| 29 | if start == -1 { |
| 30 | return nil |
| 31 | } |
| 32 | |
| 33 | data := doctype.Data[start:] |
| 34 | |
| 35 | // Remove comments to avoid false positives |
| 36 | if bytes.Contains(data, commentStart) { |
| 37 | data = entityCommentRe.ReplaceAll(data, []byte{}) |
| 38 | } |
| 39 | |
| 40 | matches := entityDeclRe.FindAllSubmatch(data, -1) |
| 41 | if matches == nil { |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | em := make(map[string][]byte, len(matches)) |
| 46 | for _, match := range matches { |
| 47 | name := match[1] |
| 48 | value := bytes.Trim(match[2], `"'`) |
| 49 | em[string(name)] = value |
| 50 | } |
| 51 | |
| 52 | return em |
| 53 | } |
| 54 | |
| 55 | // ReplaceEntitiesBytes replaces XML entities in the given byte slice |
| 56 | // according to the provided entity map. |