namespace.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package etreeutils
  2. import (
  3. "errors"
  4. "fmt"
  5. "sort"
  6. "github.com/beevik/etree"
  7. )
  8. const (
  9. defaultPrefix = ""
  10. xmlnsPrefix = "xmlns"
  11. xmlPrefix = "xml"
  12. XMLNamespace = "http://www.w3.org/XML/1998/namespace"
  13. XMLNSNamespace = "http://www.w3.org/2000/xmlns/"
  14. )
  15. var (
  16. DefaultNSContext = NSContext{
  17. prefixes: map[string]string{
  18. defaultPrefix: XMLNamespace,
  19. xmlPrefix: XMLNamespace,
  20. xmlnsPrefix: XMLNSNamespace,
  21. },
  22. }
  23. EmptyNSContext = NSContext{}
  24. ErrReservedNamespace = errors.New("disallowed declaration of reserved namespace")
  25. ErrInvalidDefaultNamespace = errors.New("invalid default namespace declaration")
  26. ErrTraversalHalted = errors.New("traversal halted")
  27. )
  28. type ErrUndeclaredNSPrefix struct {
  29. Prefix string
  30. }
  31. func (e ErrUndeclaredNSPrefix) Error() string {
  32. return fmt.Sprintf("undeclared namespace prefix: '%s'", e.Prefix)
  33. }
  34. type NSContext struct {
  35. prefixes map[string]string
  36. }
  37. func (ctx NSContext) Copy() NSContext {
  38. prefixes := make(map[string]string, len(ctx.prefixes)+4)
  39. for k, v := range ctx.prefixes {
  40. prefixes[k] = v
  41. }
  42. return NSContext{prefixes: prefixes}
  43. }
  44. func (ctx NSContext) declare(prefix, namespace string) etree.Attr {
  45. ctx.prefixes[prefix] = namespace
  46. switch prefix {
  47. case defaultPrefix:
  48. return etree.Attr{
  49. Key: xmlnsPrefix,
  50. Value: namespace,
  51. }
  52. default:
  53. return etree.Attr{
  54. Space: xmlnsPrefix,
  55. Key: prefix,
  56. Value: namespace,
  57. }
  58. }
  59. }
  60. func (ctx NSContext) SubContext(el *etree.Element) (NSContext, error) {
  61. // The subcontext should inherit existing declared prefixes
  62. newCtx := ctx.Copy()
  63. // Merge new namespace declarations on top of existing ones.
  64. for _, attr := range el.Attr {
  65. if attr.Space == xmlnsPrefix {
  66. // This attribute is a namespace declaration of the form "xmlns:<prefix>"
  67. // The 'xml' namespace may only be re-declared with the name 'http://www.w3.org/XML/1998/namespace'
  68. if attr.Key == xmlPrefix && attr.Value != XMLNamespace {
  69. return ctx, ErrReservedNamespace
  70. }
  71. // The 'xmlns' namespace may not be re-declared
  72. if attr.Key == xmlnsPrefix {
  73. return ctx, ErrReservedNamespace
  74. }
  75. newCtx.declare(attr.Key, attr.Value)
  76. } else if attr.Space == defaultPrefix && attr.Key == xmlnsPrefix {
  77. // This attribute is a default namespace declaration
  78. // The xmlns namespace value may not be declared as the default namespace
  79. if attr.Value == XMLNSNamespace {
  80. return ctx, ErrInvalidDefaultNamespace
  81. }
  82. newCtx.declare(defaultPrefix, attr.Value)
  83. }
  84. }
  85. return newCtx, nil
  86. }
  87. // Prefixes returns a copy of this context's prefix map.
  88. func (ctx NSContext) Prefixes() map[string]string {
  89. prefixes := make(map[string]string, len(ctx.prefixes))
  90. for k, v := range ctx.prefixes {
  91. prefixes[k] = v
  92. }
  93. return prefixes
  94. }
  95. // LookupPrefix attempts to find a declared namespace for the specified prefix. If the prefix
  96. // is an empty string this will be the default namespace for this context. If the prefix is
  97. // undeclared in this context an ErrUndeclaredNSPrefix will be returned.
  98. func (ctx NSContext) LookupPrefix(prefix string) (string, error) {
  99. if namespace, ok := ctx.prefixes[prefix]; ok {
  100. return namespace, nil
  101. }
  102. return "", ErrUndeclaredNSPrefix{
  103. Prefix: prefix,
  104. }
  105. }
  106. // NSIterHandler is a function which is invoked with a element and its surrounding
  107. // NSContext during traversals.
  108. type NSIterHandler func(NSContext, *etree.Element) error
  109. // NSTraverse traverses an element tree, invoking the passed handler for each element
  110. // in the tree.
  111. func NSTraverse(ctx NSContext, el *etree.Element, handle NSIterHandler) error {
  112. ctx, err := ctx.SubContext(el)
  113. if err != nil {
  114. return err
  115. }
  116. err = handle(ctx, el)
  117. if err != nil {
  118. return err
  119. }
  120. // Recursively traverse child elements.
  121. for _, child := range el.ChildElements() {
  122. err := NSTraverse(ctx, child, handle)
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. return nil
  128. }
  129. // NSDetatch makes a copy of the passed element, and declares any namespaces in
  130. // the passed context onto the new element before returning it.
  131. func NSDetatch(ctx NSContext, el *etree.Element) (*etree.Element, error) {
  132. ctx, err := ctx.SubContext(el)
  133. if err != nil {
  134. return nil, err
  135. }
  136. el = el.Copy()
  137. // Build a new attribute list
  138. attrs := make([]etree.Attr, 0, len(el.Attr))
  139. // First copy over anything that isn't a namespace declaration
  140. for _, attr := range el.Attr {
  141. if attr.Space == xmlnsPrefix {
  142. continue
  143. }
  144. if attr.Space == defaultPrefix && attr.Key == xmlnsPrefix {
  145. continue
  146. }
  147. attrs = append(attrs, attr)
  148. }
  149. // Append all in-context namespace declarations
  150. for prefix, namespace := range ctx.prefixes {
  151. // Skip the implicit "xml" and "xmlns" prefix declarations
  152. if prefix == xmlnsPrefix || prefix == xmlPrefix {
  153. continue
  154. }
  155. // Also skip declararing the default namespace as XMLNamespace
  156. if prefix == defaultPrefix && namespace == XMLNamespace {
  157. continue
  158. }
  159. if prefix != defaultPrefix {
  160. attrs = append(attrs, etree.Attr{
  161. Space: xmlnsPrefix,
  162. Key: prefix,
  163. Value: namespace,
  164. })
  165. } else {
  166. attrs = append(attrs, etree.Attr{
  167. Key: xmlnsPrefix,
  168. Value: namespace,
  169. })
  170. }
  171. }
  172. sort.Sort(SortedAttrs(attrs))
  173. el.Attr = attrs
  174. return el, nil
  175. }
  176. // NSSelectOne behaves identically to NSSelectOneCtx, but uses DefaultNSContext as the
  177. // surrounding context.
  178. func NSSelectOne(el *etree.Element, namespace, tag string) (*etree.Element, error) {
  179. return NSSelectOneCtx(DefaultNSContext, el, namespace, tag)
  180. }
  181. // NSSelectOneCtx conducts a depth-first search for an element with the specified namespace
  182. // and tag. If such an element is found, a new *etree.Element is returned which is a
  183. // copy of the found element, but with all in-context namespace declarations attached
  184. // to the element as attributes.
  185. func NSSelectOneCtx(ctx NSContext, el *etree.Element, namespace, tag string) (*etree.Element, error) {
  186. var found *etree.Element
  187. err := NSFindIterateCtx(ctx, el, namespace, tag, func(ctx NSContext, el *etree.Element) error {
  188. var err error
  189. found, err = NSDetatch(ctx, el)
  190. if err != nil {
  191. return err
  192. }
  193. return ErrTraversalHalted
  194. })
  195. if err != nil {
  196. return nil, err
  197. }
  198. return found, nil
  199. }
  200. // NSFindIterate behaves identically to NSFindIterateCtx, but uses DefaultNSContext
  201. // as the surrounding context.
  202. func NSFindIterate(el *etree.Element, namespace, tag string, handle NSIterHandler) error {
  203. return NSFindIterateCtx(DefaultNSContext, el, namespace, tag, handle)
  204. }
  205. // NSFindIterateCtx conducts a depth-first traversal searching for elements with the
  206. // specified tag in the specified namespace. It uses the passed NSContext for prefix
  207. // lookups. For each such element, the passed handler function is invoked. If the
  208. // handler function returns an error traversal is immediately halted. If the error
  209. // returned by the handler is ErrTraversalHalted then nil will be returned by
  210. // NSFindIterate. If any other error is returned by the handler, that error will be
  211. // returned by NSFindIterate.
  212. func NSFindIterateCtx(ctx NSContext, el *etree.Element, namespace, tag string, handle NSIterHandler) error {
  213. err := NSTraverse(ctx, el, func(ctx NSContext, el *etree.Element) error {
  214. _ctx, err := ctx.SubContext(el)
  215. if err != nil {
  216. return err
  217. }
  218. currentNS, err := _ctx.LookupPrefix(el.Space)
  219. if err != nil {
  220. return err
  221. }
  222. // Base case, el is the sought after element.
  223. if currentNS == namespace && el.Tag == tag {
  224. return handle(ctx, el)
  225. }
  226. return nil
  227. })
  228. if err != nil && err != ErrTraversalHalted {
  229. return err
  230. }
  231. return nil
  232. }
  233. // NSFindOne behaves identically to NSFindOneCtx, but uses DefaultNSContext for
  234. // context.
  235. func NSFindOne(el *etree.Element, namespace, tag string) (*etree.Element, error) {
  236. return NSFindOneCtx(DefaultNSContext, el, namespace, tag)
  237. }
  238. // NSFindOneCtx conducts a depth-first search for the specified element. If such an element
  239. // is found a reference to it is returned.
  240. func NSFindOneCtx(ctx NSContext, el *etree.Element, namespace, tag string) (*etree.Element, error) {
  241. var found *etree.Element
  242. err := NSFindIterateCtx(ctx, el, namespace, tag, func(ctx NSContext, el *etree.Element) error {
  243. found = el
  244. return ErrTraversalHalted
  245. })
  246. if err != nil {
  247. return nil, err
  248. }
  249. return found, nil
  250. }
  251. // NSIterateChildren iterates the children of an element, invoking the passed
  252. // handler with each direct child of the element, and the context surrounding
  253. // that child.
  254. func NSIterateChildren(ctx NSContext, el *etree.Element, handle NSIterHandler) error {
  255. ctx, err := ctx.SubContext(el)
  256. if err != nil {
  257. return err
  258. }
  259. // Iterate the child elements.
  260. for _, child := range el.ChildElements() {
  261. err = handle(ctx, child)
  262. if err != nil {
  263. return err
  264. }
  265. }
  266. return nil
  267. }
  268. // NSFindIterateChildrenCtx takes an element and its surrounding context, and iterates
  269. // the children of that element searching for an element matching the passed namespace
  270. // and tag. For each such element that is found, handle is invoked with the matched
  271. // element and its own surrounding context.
  272. func NSFindChildrenIterateCtx(ctx NSContext, el *etree.Element, namespace, tag string, handle NSIterHandler) error {
  273. err := NSIterateChildren(ctx, el, func(ctx NSContext, el *etree.Element) error {
  274. _ctx, err := ctx.SubContext(el)
  275. if err != nil {
  276. return err
  277. }
  278. currentNS, err := _ctx.LookupPrefix(el.Space)
  279. if err != nil {
  280. return err
  281. }
  282. // Base case, el is the sought after element.
  283. if currentNS == namespace && el.Tag == tag {
  284. return handle(ctx, el)
  285. }
  286. return nil
  287. })
  288. if err != nil && err != ErrTraversalHalted {
  289. return err
  290. }
  291. return nil
  292. }
  293. // NSFindOneChild behaves identically to NSFindOneChildCtx, but uses
  294. // DefaultNSContext for context.
  295. func NSFindOneChild(el *etree.Element, namespace, tag string) (*etree.Element, error) {
  296. return NSFindOneChildCtx(DefaultNSContext, el, namespace, tag)
  297. }
  298. // NSFindOneCtx conducts a depth-first search for the specified element. If such an
  299. // element is found a reference to it is returned.
  300. func NSFindOneChildCtx(ctx NSContext, el *etree.Element, namespace, tag string) (*etree.Element, error) {
  301. var found *etree.Element
  302. err := NSFindChildrenIterateCtx(ctx, el, namespace, tag, func(ctx NSContext, el *etree.Element) error {
  303. found = el
  304. return ErrTraversalHalted
  305. })
  306. if err != nil && err != ErrTraversalHalted {
  307. return nil, err
  308. }
  309. return found, nil
  310. }
  311. // NSBuildParentContext recurses upward from an element in order to build an NSContext
  312. // for its immediate parent. If the element has no parent DefaultNSContext
  313. // is returned.
  314. func NSBuildParentContext(el *etree.Element) (NSContext, error) {
  315. parent := el.Parent()
  316. if parent == nil {
  317. return DefaultNSContext, nil
  318. }
  319. ctx, err := NSBuildParentContext(parent)
  320. if err != nil {
  321. return ctx, err
  322. }
  323. return ctx.SubContext(parent)
  324. }