1 16 package org.apache.commons.jxpath.ri.model.jdom; 17 18 import java.util.ArrayList ; 19 import java.util.Collections ; 20 import java.util.List ; 21 22 import org.apache.commons.jxpath.ri.QName; 23 import org.apache.commons.jxpath.ri.model.NodeIterator; 24 import org.apache.commons.jxpath.ri.model.NodePointer; 25 import org.jdom.Attribute; 26 import org.jdom.Element; 27 import org.jdom.Namespace; 28 29 35 public class JDOMAttributeIterator implements NodeIterator { 36 private NodePointer parent; 37 private QName name; 38 private List attributes; 39 private int position = 0; 40 41 public JDOMAttributeIterator(NodePointer parent, QName name) { 42 this.parent = parent; 43 this.name = name; 44 if (parent.getNode() instanceof Element) { 45 Element element = (Element) parent.getNode(); 46 String prefix = name.getPrefix(); 47 Namespace ns; 48 if (prefix != null) { 49 if (prefix.equals("xml")) { 50 ns = Namespace.XML_NAMESPACE; 51 } 52 else { 53 ns = element.getNamespace(prefix); 54 if (ns == null) { 55 attributes = Collections.EMPTY_LIST; 57 return; 58 } 59 } 60 } 61 else { 62 ns = Namespace.NO_NAMESPACE; 63 } 64 65 String lname = name.getName(); 66 if (!lname.equals("*")) { 67 attributes = new ArrayList (); 68 if (ns != null) { 69 Attribute attr = element.getAttribute(lname, ns); 70 if (attr != null) { 71 attributes.add(attr); 72 } 73 } 74 } 75 else { 76 attributes = new ArrayList (); 77 List allAttributes = element.getAttributes(); 78 for (int i = 0; i < allAttributes.size(); i++) { 79 Attribute attr = (Attribute) allAttributes.get(i); 80 if (attr.getNamespace().equals(ns)) { 81 attributes.add(attr); 82 } 83 } 84 } 85 } 86 } 87 88 162 public NodePointer getNodePointer() { 163 if (position == 0) { 164 if (!setPosition(1)) { 165 return null; 166 } 167 position = 0; 168 } 169 int index = position - 1; 170 if (index < 0) { 171 index = 0; 172 } 173 return new JDOMAttributePointer( 174 parent, 175 (Attribute) attributes.get(index)); 176 } 177 178 public int getPosition() { 179 return position; 180 } 181 182 public boolean setPosition(int position) { 183 if (attributes == null) { 184 return false; 185 } 186 this.position = position; 187 return position >= 1 && position <= attributes.size(); 188 } 189 } | Popular Tags |