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