odml.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package markup
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "golang.org/x/net/html/charset"
  8. )
  9. // ODML takes a []byte and returns a JSON []byte representation for rendering with jsTree
  10. func MarshalODML(buf []byte) []byte {
  11. od := Odml{}
  12. decoder := xml.NewDecoder(bytes.NewReader(buf))
  13. decoder.CharsetReader = charset.NewReaderLabel
  14. _ = decoder.Decode(&od)
  15. data, _ := json.Marshal(od)
  16. return data
  17. }
  18. type Section struct {
  19. Name string `json:"-" xml:"name"`
  20. Type string `json:"-" xml:"type"`
  21. Properties []Property `json:"-" xml:"property"`
  22. Text string `json:"text"`
  23. Sections []Section `json:"-" xml:"section"`
  24. Children []OdMLObject `json:"children,omitempty"`
  25. }
  26. type Property struct {
  27. Name string `json:"-" xml:"name"`
  28. Value []string `json:"-" xml:"value"`
  29. Text string `json:"text"`
  30. Icon string
  31. Definition string `xml:"definition"`
  32. }
  33. type OdMLObject struct {
  34. Prop Property
  35. Section Section
  36. Type string
  37. }
  38. type Odml struct {
  39. OdmnlSections []Section `json:"children" xml:"section"`
  40. }
  41. func (u *Property) MarshalJSON() ([]byte, error) {
  42. type Alias Property
  43. if u.Text == "" {
  44. u.Text = fmt.Sprintf("%s: %s (%s)", u.Name, u.Value, u.Definition)
  45. }
  46. return json.Marshal(Alias(*u))
  47. }
  48. func (u *Section) MarshalJSON() ([]byte, error) {
  49. type Alias Section
  50. if u.Text == "" {
  51. u.Text = u.Name
  52. }
  53. for _, x := range u.Properties {
  54. u.Children = append(u.Children, OdMLObject{Prop: x, Type: "property"})
  55. }
  56. for _, x := range u.Sections {
  57. u.Children = append(u.Children, OdMLObject{Section: x, Type: "section"})
  58. }
  59. return json.Marshal(Alias(*u))
  60. }
  61. func (u *OdMLObject) MarshalJSON() ([]byte, error) {
  62. if u.Type == "property" {
  63. return u.Prop.MarshalJSON()
  64. }
  65. if u.Type == "section" {
  66. return u.Section.MarshalJSON()
  67. }
  68. return nil, fmt.Errorf("Could not unmarshal odml object")
  69. }