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