| 1 | package xmltransformer |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | ) |
| 6 | |
| 7 | type uniqueKeyGenerator interface { |
| 8 | Gen(key string) string |
| 9 | GenAttribute(key, attr string) string |
| 10 | } |
| 11 | |
| 12 | type uniqueKeyGeneratorImpl struct { |
| 13 | keyCounters map[string]int |
| 14 | } |
| 15 | |
| 16 | func NewUniqueKeyGenerator() uniqueKeyGenerator { |
| 17 | return &uniqueKeyGeneratorImpl{ |
| 18 | keyCounters: make(map[string]int), |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | func (u *uniqueKeyGeneratorImpl) Gen(key string) string { |
| 23 | count, _ := u.keyCounters[key] |
| 24 | u.keyCounters[key]++ |
| 25 | if count > 0 { |
| 26 | return fmt.Sprintf("%v~%v", key, count) |
| 27 | } |
| 28 | return key |
| 29 | } |
| 30 | |
| 31 | func (u *uniqueKeyGeneratorImpl) GenAttribute(key, attr string) string { |
| 32 | attrPath := fmt.Sprintf("%v[%v]", key, attr) |
| 33 | count, _ := u.keyCounters[attrPath] |
| 34 | u.keyCounters[attrPath]++ |
| 35 | if count > 0 { |
| 36 | return fmt.Sprintf("%v[%v~%v]", key, attr, count) |
| 37 | } |
| 38 | return attrPath |
| 39 | } |