1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jxpath.ri.model.dom;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.commons.jxpath.ri.model.NodeIterator;
23 import org.apache.commons.jxpath.ri.model.NodePointer;
24 import org.w3c.dom.Attr;
25 import org.w3c.dom.Document;
26 import org.w3c.dom.NamedNodeMap;
27 import org.w3c.dom.Node;
28
29
30
31
32
33
34
35 public class DOMNamespaceIterator implements NodeIterator {
36 private NodePointer parent;
37 private List attributes;
38 private int position = 0;
39
40
41
42
43
44 public DOMNamespaceIterator(NodePointer parent) {
45 this.parent = parent;
46 attributes = new ArrayList();
47 collectNamespaces(attributes, (Node) parent.getNode());
48 }
49
50
51
52
53
54
55 private void collectNamespaces(List attributes, Node node) {
56 Node parent = node.getParentNode();
57 if (parent != null) {
58 collectNamespaces(attributes, parent);
59 }
60 if (node.getNodeType() == Node.DOCUMENT_NODE) {
61 node = ((Document) node).getDocumentElement();
62 }
63 if (node.getNodeType() == Node.ELEMENT_NODE) {
64 NamedNodeMap map = node.getAttributes();
65 int count = map.getLength();
66 for (int i = 0; i < count; i++) {
67 Attr attr = (Attr) map.item(i);
68 String prefix = DOMNodePointer.getPrefix(attr);
69 String name = DOMNodePointer.getLocalName(attr);
70 if ((prefix != null && prefix.equals("xmlns"))
71 || (prefix == null && name.equals("xmlns"))) {
72 attributes.add(attr);
73 }
74 }
75 }
76 }
77
78 public NodePointer getNodePointer() {
79 if (position == 0) {
80 if (!setPosition(1)) {
81 return null;
82 }
83 position = 0;
84 }
85 int index = position - 1;
86 if (index < 0) {
87 index = 0;
88 }
89 String prefix = "";
90 Attr attr = (Attr) attributes.get(index);
91 String name = attr.getPrefix();
92 if (name != null && name.equals("xmlns")) {
93 prefix = DOMNodePointer.getLocalName(attr);
94 }
95 return new NamespacePointer(parent, prefix, attr.getValue());
96 }
97
98 public int getPosition() {
99 return position;
100 }
101
102 public boolean setPosition(int position) {
103 this.position = position;
104 return position >= 1 && position <= attributes.size();
105 }
106 }