MCPcopy Create free account
hub / github.com/aws/smithy-go / StructToXML

Function StructToXML

testing/xml/xmlToStruct.go:135–207  ·  view source on GitHub ↗

StructToXML writes an XMLNode to a xml.Encoder as tokens.

(e *xml.Encoder, node *XMLNode, sorted bool)

Source from the content-addressed store, hash-verified

133
134// StructToXML writes an XMLNode to a xml.Encoder as tokens.
135func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error {
136 var err error
137 // Sort Attributes
138 attrs := node.Attr
139 if sorted {
140 sortedAttrs := make([]xml.Attr, 0, len(attrs))
141 for _, k := range node.Attr {
142 sortedAttrs = append(sortedAttrs, k)
143 }
144 sort.Sort(xmlAttrSlice(sortedAttrs))
145 attrs = sortedAttrs
146 }
147
148 // Filter out default xmlns attributes that encoding/xml will regenerate
149 // from Name.Space. Without this, XML produced with literal xmlns
150 // attributes (rather than through encoding/xml's namespace-aware API)
151 // gets those declarations doubled on re-encode. Prefixed namespace
152 // declarations (xmlns:prefix="...") are preserved since the encoder
153 // does not regenerate those.
154 filtered := make([]xml.Attr, 0, len(attrs))
155 for _, a := range attrs {
156 if a.Name.Space == "" && a.Name.Local == "xmlns" {
157 continue
158 }
159 filtered = append(filtered, a)
160 }
161
162 st := xml.StartElement{Name: node.Name, Attr: filtered}
163 e.EncodeToken(st)
164 // return fmt.Errorf("encoder string : %s, %s, %s", node.Name.Local, node.Name.Space, st.Attr)
165
166 if node.Text != "" {
167 e.EncodeToken(xml.CharData([]byte(node.Text)))
168 } else if sorted {
169 sortedNames := []string{}
170 for k := range node.Children {
171 sortedNames = append(sortedNames, k)
172 }
173 sort.Strings(sortedNames)
174
175 for _, k := range sortedNames {
176 // we should sort the []*xml.Node for each key if len >1
177 flattenedNodes := node.Children[k]
178 // Meaning this has multiple nodes
179 if len(flattenedNodes) > 1 {
180 // sort flattened nodes
181 flattenedNodes, err = sortFlattenedNodes(flattenedNodes)
182 if err != nil {
183 return err
184 }
185 }
186
187 for _, v := range flattenedNodes {
188 err = StructToXML(e, v, sorted)
189 if err != nil {
190 return err
191 }
192 }

Callers 1

SortXMLFunction · 0.85

Calls 2

xmlAttrSliceTypeAlias · 0.85
sortFlattenedNodesFunction · 0.85

Tested by

no test coverage detected