struct.go 978 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package xml2json
  2. import (
  3. "strings"
  4. )
  5. // Node is a data element on a tree
  6. type Node struct {
  7. Children map[string]Nodes
  8. Data string
  9. ChildrenAlwaysAsArray bool
  10. }
  11. // Nodes is a list of nodes
  12. type Nodes []*Node
  13. // AddChild appends a node to the list of children
  14. func (n *Node) AddChild(s string, c *Node) {
  15. // Lazy lazy
  16. if n.Children == nil {
  17. n.Children = map[string]Nodes{}
  18. }
  19. n.Children[s] = append(n.Children[s], c)
  20. }
  21. // IsComplex returns whether it is a complex type (has children)
  22. func (n *Node) IsComplex() bool {
  23. return len(n.Children) > 0
  24. }
  25. // GetChild returns child by path if exists. Path looks like "grandparent.parent.child.grandchild"
  26. func (n *Node) GetChild(path string) *Node {
  27. result := n
  28. names := strings.Split(path, ".")
  29. for _, name := range names {
  30. children, exists := result.Children[name]
  31. if !exists {
  32. return nil
  33. }
  34. if len(children) == 0 {
  35. return nil
  36. }
  37. result = children[0]
  38. }
  39. return result
  40. }