10 // A XMLNode contains the values to be encoded or decoded.
12 Name xml.Name `json:",omitempty"`
13 Children map[string][]*XMLNode `json:",omitempty"`
14 Text string `json:",omitempty"`
15 Attr []xml.Attr `json:",omitempty"`
17 namespaces map[string]string
21 // NewXMLElement returns a pointer to a new XMLNode initialized to default values.
22 func NewXMLElement(name xml.Name) *XMLNode {
25 Children: map[string][]*XMLNode{},
30 // AddChild adds child to the XMLNode.
31 func (n *XMLNode) AddChild(child *XMLNode) {
33 if _, ok := n.Children[child.Name.Local]; !ok {
34 n.Children[child.Name.Local] = []*XMLNode{}
36 n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child)
39 // XMLToStruct converts a xml.Decoder stream to XMLNode with nested values.
40 func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) {
56 switch typed := tok.(type) {
58 out.Text = string(typed.Copy())
59 case xml.StartElement:
62 if out.Children == nil {
63 out.Children = map[string][]*XMLNode{}
66 name := typed.Name.Local
67 slice := out.Children[name]
71 node, e := XMLToStruct(d, &el)
76 node.Name = typed.Name
79 // Save into a temp variable, simply because out gets squashed during
81 node.parent = &tempOut
82 slice = append(slice, node)
83 out.Children[name] = slice
85 if s != nil && s.Name.Local == typed.Name.Local { // matching end token
94 func (n *XMLNode) findNamespaces() {
95 ns := map[string]string{}
96 for _, a := range n.Attr {
97 if a.Name.Space == "xmlns" {
98 ns[a.Value] = a.Name.Local
105 func (n *XMLNode) findElem(name string) (string, bool) {
106 for node := n; node != nil; node = node.parent {
107 for _, a := range node.Attr {
108 namespace := a.Name.Space
109 if v, ok := node.namespaces[namespace]; ok {
112 if name == fmt.Sprintf("%s:%s", namespace, a.Name.Local) {
120 // StructToXML writes an XMLNode to a xml.Encoder as tokens.
121 func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error {
122 e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr})
125 e.EncodeToken(xml.CharData([]byte(node.Text)))
127 sortedNames := []string{}
128 for k := range node.Children {
129 sortedNames = append(sortedNames, k)
131 sort.Strings(sortedNames)
133 for _, k := range sortedNames {
134 for _, v := range node.Children[k] {
135 StructToXML(e, v, sorted)
139 for _, c := range node.Children {
140 for _, v := range c {
141 StructToXML(e, v, sorted)
146 e.EncodeToken(xml.EndElement{Name: node.Name})