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.Collections;
21 import java.util.List;
22
23 import org.apache.commons.jxpath.ri.QName;
24 import org.apache.commons.jxpath.ri.model.NodeIterator;
25 import org.apache.commons.jxpath.ri.model.NodePointer;
26 import org.jdom.Attribute;
27 import org.jdom.Element;
28 import org.jdom.Namespace;
29
30
31
32
33
34
35
36 public class JDOMAttributeIterator implements NodeIterator {
37 private NodePointer parent;
38 private List attributes;
39 private int position = 0;
40
41
42
43
44
45
46 public JDOMAttributeIterator(NodePointer parent, QName name) {
47 this.parent = parent;
48 if (parent.getNode() instanceof Element) {
49 Element element = (Element) parent.getNode();
50 String prefix = name.getPrefix();
51 Namespace ns = null;
52 if (prefix != null) {
53 if (prefix.equals("xml")) {
54 ns = Namespace.XML_NAMESPACE;
55 }
56 else {
57 String uri = parent.getNamespaceResolver().getNamespaceURI(prefix);
58 if (uri != null) {
59 ns = Namespace.getNamespace(prefix, uri);
60 }
61 if (ns == null) {
62
63 attributes = Collections.EMPTY_LIST;
64 return;
65 }
66 }
67 }
68 else {
69 ns = Namespace.NO_NAMESPACE;
70 }
71
72 String lname = name.getName();
73 if (!lname.equals("*")) {
74 attributes = new ArrayList();
75 Attribute attr = element.getAttribute(lname, ns);
76 if (attr != null) {
77 attributes.add(attr);
78 }
79 }
80 else {
81 attributes = new ArrayList();
82 List allAttributes = element.getAttributes();
83 for (int i = 0; i < allAttributes.size(); i++) {
84 Attribute attr = (Attribute) allAttributes.get(i);
85 if (ns == Namespace.NO_NAMESPACE
86 || attr.getNamespace().equals(ns)) {
87 attributes.add(attr);
88 }
89 }
90 }
91 }
92 }
93
94 public NodePointer getNodePointer() {
95 if (position == 0) {
96 if (!setPosition(1)) {
97 return null;
98 }
99 position = 0;
100 }
101 int index = position - 1;
102 if (index < 0) {
103 index = 0;
104 }
105 return new JDOMAttributePointer(
106 parent,
107 (Attribute) attributes.get(index));
108 }
109
110 public int getPosition() {
111 return position;
112 }
113
114 public boolean setPosition(int position) {
115 if (attributes == null) {
116 return false;
117 }
118 this.position = position;
119 return position >= 1 && position <= attributes.size();
120 }
121 }