| 1 | package xmltransformer |
| 2 | |
| 3 | import ( |
| 4 | "encoding/xml" |
| 5 | ) |
| 6 | |
| 7 | type xmlStack interface { |
| 8 | Push(v xml.StartElement) |
| 9 | Pop() stackElement |
| 10 | Peek() stackElement |
| 11 | } |
| 12 | |
| 13 | type xmlStackImpl struct { |
| 14 | stack []*stackElementImpl |
| 15 | keyGen uniqueKeyGenerator |
| 16 | } |
| 17 | |
| 18 | func newXMLStack() xmlStack { |
| 19 | return &xmlStackImpl{ |
| 20 | keyGen: NewUniqueKeyGenerator(), |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | func (s *xmlStackImpl) Push(v xml.StartElement) { |
| 25 | element := &stackElementImpl{ |
| 26 | name: v.Name.Local, |
| 27 | } |
| 28 | s.stack = append(s.stack, element) |
| 29 | |
| 30 | element.path = s.keyGen.Gen(s.currPath()) |
| 31 | element.attr = make(map[string]string, len(v.Attr)) |
| 32 | for _, attr := range v.Attr { |
| 33 | attrPath := s.keyGen.GenAttribute(element.path, attr.Name.Local) |
| 34 | element.attr[attrPath] = attr.Value |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func (s *xmlStackImpl) Pop() stackElement { |
| 39 | l := len(s.stack) |
| 40 | if l == 0 { |
| 41 | return nil |
| 42 | } |
| 43 | |
| 44 | res := s.stack[l-1] |
| 45 | s.stack = s.stack[:l-1] |
| 46 | return res |
| 47 | } |
| 48 | |
| 49 | func (s *xmlStackImpl) Peek() stackElement { |
| 50 | l := len(s.stack) |
| 51 | if l == 0 { |
| 52 | return nil |
| 53 | } |
| 54 | |
| 55 | return s.stack[l-1] |
| 56 | } |
| 57 | |
| 58 | func (s *xmlStackImpl) currPath() (path string) { |
| 59 | for _, e := range s.stack { |
| 60 | if len(path) != 0 { |
| 61 | path += "." |
| 62 | } |
| 63 | path += e.name |
| 64 | } |
| 65 | return path |
| 66 | } |
| 67 | |
| 68 | type stackElement interface { |
| 69 | Path() string |
| 70 | Attributes() map[string]string |
| 71 | CharData() []string |
| 72 | AppendCharData(charData string) |
| 73 | } |
| 74 | |
| 75 | type stackElementImpl struct { |
| 76 | name string |
| 77 | path string |
| 78 | attr map[string]string |
| 79 | charData []string |
| 80 | } |
| 81 | |
| 82 | func (e *stackElementImpl) Path() string { |
| 83 | return e.path |
| 84 | } |
| 85 | |
| 86 | func (e *stackElementImpl) Attributes() map[string]string { |
| 87 | return e.attr |
| 88 | } |
| 89 | |
| 90 | func (e *stackElementImpl) CharData() []string { |
| 91 | return e.charData |
| 92 | } |
| 93 | |
| 94 | func (e *stackElementImpl) AppendCharData(charData string) { |
| 95 | e.charData = append(e.charData, charData) |
| 96 | } |