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