1 16 package org.apache.commons.jxpath.ri.model.jdom; 17 18 import java.util.ArrayList ; 19 import java.util.HashSet ; 20 import java.util.List ; 21 import java.util.Set ; 22 23 import org.apache.commons.jxpath.ri.model.NodeIterator; 24 import org.apache.commons.jxpath.ri.model.NodePointer; 25 import org.jdom.Document; 26 import org.jdom.Element; 27 import org.jdom.Namespace; 28 29 35 public class JDOMNamespaceIterator implements NodeIterator { 36 private NodePointer parent; 37 private List namespaces; 38 private Set prefixes; 39 private int position = 0; 40 41 public JDOMNamespaceIterator(NodePointer parent) { 42 this.parent = parent; 43 Object node = parent.getNode(); 44 if (node instanceof Document) { 45 node = ((Document)node).getRootElement(); 46 } 47 if (node instanceof Element) { 48 namespaces = new ArrayList (); 49 prefixes = new HashSet (); 50 collectNamespaces((Element) node); 51 } 52 } 53 54 private void collectNamespaces(Element element) { 55 Namespace ns = element.getNamespace(); 56 if (ns != null && !prefixes.contains(ns.getPrefix())) { 57 namespaces.add(ns); 58 prefixes.add(ns.getPrefix()); 59 } 60 List others = element.getAdditionalNamespaces(); 61 for (int i = 0; i < others.size(); i++) { 62 ns = (Namespace) others.get(i); 63 if (ns != null && !prefixes.contains(ns.getPrefix())) { 64 namespaces.add(ns); 65 prefixes.add(ns.getPrefix()); 66 } 67 } 68 Object parent = element.getParent(); 69 if (parent instanceof Element) { 70 collectNamespaces((Element)parent); 71 } 72 } 73 74 public NodePointer getNodePointer() { 75 if (position == 0) { 76 if (!setPosition(1)) { 77 return null; 78 } 79 position = 0; 80 } 81 int index = position - 1; 82 if (index < 0) { 83 index = 0; 84 } 85 Namespace ns = (Namespace) namespaces.get(index); 86 return new JDOMNamespacePointer(parent, ns.getPrefix(), ns.getURI()); 87 } 88 89 public int getPosition() { 90 return position; 91 } 92 93 public boolean setPosition(int position) { 94 if (namespaces == null) { 95 return false; 96 } 97 this.position = position; 98 return position >= 1 && position <= namespaces.size(); 99 } 100 } | Popular Tags |