json2xml.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package util
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "fmt"
  6. "io"
  7. )
  8. // Copyright 2021 Patrick Gundlach
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software
  10. // and associated documentation files (the "Software"), to deal in the Software without restriction,
  11. // including without limitation the rights to use, copy, modify, merge, publish, distribute,
  12. // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  13. // furnished to do so, subject to the following conditions:
  14. // The above copyright notice and this permission notice shall be included in all copies or
  15. // substantial portions of the Software.
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  17. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  18. // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
  20. // OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. // encodeString encodes str as an element named entry with the attribute key="<value of key>" if key is not empty.
  22. func encodeString(enc *xml.Encoder, str string, key string) error {
  23. stringElt := xml.StartElement{Name: xml.Name{Local: "entry"}}
  24. var err error
  25. if key != "" {
  26. stringElt.Attr = []xml.Attr{{Name: xml.Name{Local: "key"}, Value: key}}
  27. }
  28. if err = enc.EncodeToken(stringElt); err != nil {
  29. return err
  30. }
  31. if err = enc.EncodeToken(xml.CharData([]byte(str))); err != nil {
  32. return err
  33. }
  34. return enc.EncodeToken(stringElt.End())
  35. }
  36. // ToXML reads the JSON file from jsonInput and writes to xmlOutput.
  37. func ToXML(jsonInput io.Reader, xmlOutput io.Writer) error {
  38. var err error
  39. dec := json.NewDecoder(jsonInput)
  40. enc := xml.NewEncoder(xmlOutput)
  41. root := xml.StartElement{}
  42. root.Name = xml.Name{Local: "Root"}
  43. mapElt := xml.StartElement{Name: xml.Name{Local: "map"}}
  44. aryElt := xml.StartElement{Name: xml.Name{Local: "array"}}
  45. // inMap is a stack with the last element shows if we are currently
  46. // in a map. This is to insert key=".." attributes.
  47. inMap := []bool{false}
  48. err = enc.EncodeToken(root)
  49. if err != nil {
  50. return err
  51. }
  52. var key string
  53. encodeLoop:
  54. for {
  55. tok, err := dec.Token()
  56. if err != nil && err != io.EOF {
  57. return err
  58. }
  59. if tok == nil {
  60. break encodeLoop
  61. }
  62. switch t := tok.(type) {
  63. case json.Delim:
  64. switch t {
  65. case '{':
  66. inMap = append(inMap, true)
  67. if key == "" {
  68. if enc.EncodeToken(mapElt); err != nil {
  69. return err
  70. }
  71. } else {
  72. attr := xml.Attr{Name: xml.Name{Local: "key"}, Value: key}
  73. se := mapElt.Copy()
  74. se.Attr = []xml.Attr{attr}
  75. if err = enc.EncodeToken(se); err != nil {
  76. return err
  77. }
  78. }
  79. key = ""
  80. case '[':
  81. inMap = append(inMap, false)
  82. if key == "" {
  83. if err = enc.EncodeToken(aryElt); err != nil {
  84. return err
  85. }
  86. } else {
  87. attr := xml.Attr{Name: xml.Name{Local: "key"}, Value: key}
  88. se := aryElt.Copy()
  89. se.Attr = []xml.Attr{attr}
  90. if err = enc.EncodeToken(se); err != nil {
  91. return err
  92. }
  93. }
  94. key = ""
  95. case ']':
  96. inMap = inMap[:len(inMap)-1]
  97. if key != "" {
  98. if err = encodeString(enc, key, ""); err != nil {
  99. return err
  100. }
  101. key = ""
  102. }
  103. if err = enc.EncodeToken(aryElt.End()); err != nil {
  104. return err
  105. }
  106. case '}':
  107. inMap = inMap[:len(inMap)-1]
  108. if key != "" {
  109. if err = encodeString(enc, key, ""); err != nil {
  110. return err
  111. }
  112. key = ""
  113. }
  114. if err = enc.EncodeToken(mapElt.End()); err != nil {
  115. return err
  116. }
  117. }
  118. case string:
  119. if inMap[len(inMap)-1] {
  120. if key != "" {
  121. if err = encodeString(enc, t, key); err != nil {
  122. return err
  123. }
  124. key = ""
  125. } else {
  126. key = t
  127. }
  128. } else {
  129. if err = encodeString(enc, t, ""); err != nil {
  130. return err
  131. }
  132. }
  133. case float64, bool:
  134. if err = encodeString(enc, fmt.Sprint(t), key); err != nil {
  135. return err
  136. }
  137. key = ""
  138. default:
  139. panic("not implemented")
  140. }
  141. }
  142. if err = enc.EncodeToken(root.End()); err != nil {
  143. return err
  144. }
  145. return enc.Flush()
  146. }