undoEncoderNamespaces undoes, in after, the namespace declarations that xml.Encoder adds when it encodes before. RawToken leaves a prefix in Name.Space, which the encoder treats as a namespace URI: it writes a prefixed element name as the local name with a default namespace declaration (xmlns="pref
(before, after xml.StartElement)
| 313 | // (xmlns:gen="prefix") just before the attribute. Mapping these back gives |
| 314 | // the names before had, if the token is stable. |
| 315 | func undoEncoderNamespaces(before, after xml.StartElement) xml.StartElement { |
| 316 | if len(after.Attr) <= len(before.Attr) { |
| 317 | return after |
| 318 | } |
| 319 | attrs := make([]xml.Attr, len(after.Attr)) |
| 320 | copy(attrs, after.Attr) |
| 321 | |
| 322 | if before.Name.Space != "" && after.Name.Space == "" && len(attrs) > 0 && attrs[0].Name == (xml.Name{Local: "xmlns"}) { |
| 323 | after.Name.Space = attrs[0].Value |
| 324 | attrs = attrs[1:] |
| 325 | } |
| 326 | |
| 327 | for len(attrs) > len(before.Attr) && len(attrs) > 1 { |
| 328 | i := 1 |
| 329 | for ; i < len(attrs); i++ { |
| 330 | if attrs[i-1].Name.Space == "xmlns" && attrs[i-1].Name.Local == attrs[i].Name.Space { |
| 331 | break |
| 332 | } |
| 333 | } |
| 334 | if i == len(attrs) { |
| 335 | break |
| 336 | } |
| 337 | prefix, uri := attrs[i-1].Name.Local, attrs[i-1].Value |
| 338 | attrs = append(attrs[:i-1], attrs[i:]...) |
| 339 | for j := range attrs { |
| 340 | if attrs[j].Name.Space == prefix { |
| 341 | attrs[j].Name.Space = uri |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | after.Attr = attrs |
| 346 | return after |
| 347 | } |