encodeEtreeElement writes el to e with its prefixes intact. scope holds the prefixes declared by the ancestors already written ("" is the default namespace); a prefix that el uses but is declared outside the subtree being written is looked up on el's real ancestors and declared on el.
(e *xml.Encoder, el *etree.Element, scope map[string]bool)
| 36 | // namespace); a prefix that el uses but is declared outside the subtree being |
| 37 | // written is looked up on el's real ancestors and declared on el. |
| 38 | func encodeEtreeElement(e *xml.Encoder, el *etree.Element, scope map[string]bool) error { |
| 39 | declared := make(map[string]bool, len(scope)+2) |
| 40 | for prefix := range scope { |
| 41 | declared[prefix] = true |
| 42 | } |
| 43 | |
| 44 | start := xml.StartElement{Name: xml.Name{Local: qualifiedName(el.Space, el.Tag)}} |
| 45 | for _, attr := range el.Attr { |
| 46 | start.Attr = append(start.Attr, xml.Attr{ |
| 47 | Name: xml.Name{Local: qualifiedName(attr.Space, attr.Key)}, |
| 48 | Value: attr.Value, |
| 49 | }) |
| 50 | switch { |
| 51 | case attr.Space == "xmlns": |
| 52 | declared[attr.Key] = true |
| 53 | case attr.Space == "" && attr.Key == "xmlns": |
| 54 | declared[""] = true |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // Declare the prefixes el and its attributes use but do not have in |
| 59 | // scope, so the output never depends on namespaces declared on elements |
| 60 | // that are not written. |
| 61 | if !declared[el.Space] { |
| 62 | start.Attr = append(start.Attr, namespaceDeclaration(el.Space, el.NamespaceURI())) |
| 63 | declared[el.Space] = true |
| 64 | } |
| 65 | for i := range el.Attr { |
| 66 | attr := &el.Attr[i] |
| 67 | if attr.Space == "" || attr.Space == "xmlns" || declared[attr.Space] { |
| 68 | continue |
| 69 | } |
| 70 | start.Attr = append(start.Attr, namespaceDeclaration(attr.Space, attr.NamespaceURI())) |
| 71 | declared[attr.Space] = true |
| 72 | } |
| 73 | |
| 74 | if err := e.EncodeToken(start); err != nil { |
| 75 | return err |
| 76 | } |
| 77 | for _, child := range el.Child { |
| 78 | var err error |
| 79 | switch child := child.(type) { |
| 80 | case *etree.Element: |
| 81 | err = encodeEtreeElement(e, child, declared) |
| 82 | case *etree.CharData: |
| 83 | err = e.EncodeToken(xml.CharData(child.Data)) |
| 84 | case *etree.Comment: |
| 85 | err = e.EncodeToken(xml.Comment(child.Data)) |
| 86 | } |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | } |
| 91 | return e.EncodeToken(start.End()) |
| 92 | } |
| 93 | |
| 94 | func qualifiedName(prefix, local string) string { |
| 95 | if prefix == "" { |
no test coverage detected