1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
package etreeutils
import "github.com/beevik/etree"
// SortedAttrs provides sorting capabilities, compatible with XML C14N, on top
// of an []etree.Attr
type SortedAttrs []etree.Attr
func (a SortedAttrs) Len() int {
return len(a)
}
func (a SortedAttrs) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a SortedAttrs) Less(i, j int) bool {
// This is the best reference I've found on sort order:
// http://dst.lbl.gov/~ksb/Scratch/XMLC14N.html
// If attr j is a default namespace declaration, attr i may
// not be strictly "less" than it.
if a[j].Space == defaultPrefix && a[j].Key == xmlnsPrefix {
return false
}
// Otherwise, if attr i is a default namespace declaration, it
// must be less than anything else.
if a[i].Space == defaultPrefix && a[i].Key == xmlnsPrefix {
return true
}
// Next, namespace prefix declarations, sorted by prefix, come before
// anythign else.
if a[i].Space == xmlnsPrefix {
if a[j].Space == xmlnsPrefix {
return a[i].Key < a[j].Key
}
return true
}
if a[j].Space == xmlnsPrefix {
return false
}
// Then come unprefixed attributes, sorted by key.
if a[i].Space == defaultPrefix {
if a[j].Space == defaultPrefix {
return a[i].Key < a[j].Key
}
return true
}
if a[j].Space == defaultPrefix {
return false
}
// Wow. We're still going. Finally, attributes in the same namespace should be
// sorted by key. Attributes in different namespaces should be sorted by the
// actual namespace (_not_ the prefix). For now just use the prefix.
if a[i].Space == a[j].Space {
return a[i].Key < a[j].Key
}
return a[i].Space < a[j].Space
}
|