1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.jxpath.ri.model.jdom;
19
20 import java.util.ArrayList;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Set;
24
25 import org.apache.commons.jxpath.ri.model.NodeIterator;
26 import org.apache.commons.jxpath.ri.model.NodePointer;
27 import org.jdom.Document;
28 import org.jdom.Element;
29 import org.jdom.Namespace;
30
31
32
33
34 public class JDOMNamespaceIterator implements NodeIterator {
35
36 private final NodePointer parent;
37 private List<Namespace> namespaces;
38 private Set<String> prefixes;
39 private int position;
40
41
42
43
44
45
46 public JDOMNamespaceIterator(final NodePointer parent) {
47 this.parent = parent;
48 Object node = parent.getNode();
49 if (node instanceof Document) {
50 node = ((Document) node).getRootElement();
51 }
52 if (node instanceof Element) {
53 namespaces = new ArrayList<>();
54 prefixes = new HashSet<>();
55 collectNamespaces((Element) node);
56 }
57 }
58
59
60
61
62
63
64 private void collectNamespaces(final Element element) {
65 Namespace ns = element.getNamespace();
66 if (ns != null && !prefixes.contains(ns.getPrefix())) {
67 namespaces.add(ns);
68 prefixes.add(ns.getPrefix());
69 }
70 final List others = element.getAdditionalNamespaces();
71 for (final Object other : others) {
72 ns = (Namespace) other;
73 if (ns != null && !prefixes.contains(ns.getPrefix())) {
74 namespaces.add(ns);
75 prefixes.add(ns.getPrefix());
76 }
77 }
78 final Object elementParent = element.getParent();
79 if (elementParent instanceof Element) {
80 collectNamespaces((Element) elementParent);
81 }
82 }
83
84 @Override
85 public NodePointer getNodePointer() {
86 if (position == 0) {
87 if (!setPosition(1)) {
88 return null;
89 }
90 position = 0;
91 }
92 int index = position - 1;
93 if (index < 0) {
94 index = 0;
95 }
96 final Namespace ns = namespaces.get(index);
97 return new JDOMNamespacePointer(parent, ns.getPrefix(), ns.getURI());
98 }
99
100 @Override
101 public int getPosition() {
102 return position;
103 }
104
105 @Override
106 public boolean setPosition(final int position) {
107 if (namespaces == null) {
108 return false;
109 }
110 this.position = position;
111 return position >= 1 && position <= namespaces.size();
112 }
113 }