1 19 20 package org.netbeans.modules.xml.xdm.visitor; 21 22 import java.util.ArrayList ; 23 import java.util.HashMap ; 24 import java.util.List ; 25 import java.util.Map ; 26 import org.netbeans.modules.xml.xdm.nodes.Attribute; 27 import org.netbeans.modules.xml.xdm.nodes.Element; 28 import org.netbeans.modules.xml.xdm.nodes.Node; 29 import org.netbeans.modules.xml.xdm.nodes.Document; 30 import org.w3c.dom.NamedNodeMap ; 31 32 36 public class FindNamespaceVisitor extends ChildVisitor { 37 38 39 public FindNamespaceVisitor(Document root) { 40 this.root = root; 41 } 42 43 public String findNamespace(Node target) { 44 if(!(target instanceof Element) && !(target instanceof Attribute)) return null; 45 return getNamespaceMap().get(target.getId()); 46 } 47 48 public Map <Integer ,String > getNamespaceMap() { 49 if(namespaceMap.isEmpty()) { 50 nodeCtr = 0; 51 visit(root); 52 } 53 return namespaceMap; 54 } 55 56 protected void visitNode(Node node) { 57 Map <String ,String > namespaces = new HashMap <String ,String >(); 58 if((node instanceof Element) || (node instanceof Attribute)) { 59 nodeCtr++; 60 boolean found = false; 61 String prefix = node.getPrefix(); 62 if(prefix == null) { 63 if(node instanceof Attribute) return; 64 prefix = ""; 65 } 66 if(node instanceof Element && node.hasAttributes()) { 67 NamedNodeMap attrMap = node.getAttributes(); 68 for (int i=0;i<attrMap.getLength();i++) { 69 Attribute attribute = (Attribute)attrMap.item(i); 70 if(Element.XMLNS.equals(attribute.getPrefix()) || Element.XMLNS.equals(attribute.getName())) { 71 String key = attribute.getPrefix()==null?"":attribute.getLocalName(); 72 String value = attribute.getValue(); 73 namespaces.put(key,value); 74 if(key.equals(prefix)) { 75 namespaceMap.put(node.getId(),value); 76 found = true; 77 } 78 } 79 } 80 } 81 if(!found) { 82 for(Map <String ,String > map:ancestorNamespaceMaps) { 83 if(map.containsKey(prefix)) { 84 namespaceMap.put(node.getId(),map.get(prefix)); 85 break; 86 } 87 } 88 } 89 } 90 if(!namespaces.isEmpty()) 91 ancestorNamespaceMaps.add(0,namespaces); 92 super.visitNode(node); 93 ancestorNamespaceMaps.remove(namespaces); 94 } 95 96 private Map <Integer ,String > namespaceMap = new HashMap <Integer ,String >(); 97 private Document root = null; 98 private List <Map <String ,String >> ancestorNamespaceMaps = new ArrayList <Map <String ,String >>(); 99 int nodeCtr; 100 } 101 | Popular Tags |