NamespaceUtils { public static List<Namespace> getNamespacesInScope(Element element) { TreeMap<String, Namespace> namespaces = new TreeMap<String, Namespace>(); namespaces.put(Namespace.XML_NAMESPACE.getPrefix(), Namespace.XML_NAMESPACE); namespaces.put(element.getNamespacePrefix(), element.getNamespace()); if (element.getAdditionalNamespaces() != null) { for (Object nso : element.getAdditionalNamespaces()) { Namespace ns = (Namespace) nso; if (!namespaces.containsKey(ns.getPrefix())) { namespaces.put(ns.getPrefix(), ns); } } } if (element.getAttributes() != null) { for (Object attO : element.getAttributes()) { Attribute att = (Attribute) attO; Namespace ns = att.getNamespace(); if (!namespaces.containsKey(ns.getPrefix())) { namespaces.put(ns.getPrefix(), ns); } } } final Element pnt = element.getParentElement(); if (pnt != null) { for (Namespace ns : getNamespacesInScope(pnt)) { if (!namespaces.containsKey(ns.getPrefix())) { namespaces.put(ns.getPrefix(), ns); } } } if (pnt == null && !namespaces.containsKey("")) { namespaces.put(Namespace.NO_NAMESPACE.getPrefix(), Namespace.NO_NAMESPACE); } ArrayList<Namespace> al = new ArrayList<Namespace>(namespaces.size()); al.add(element.getNamespace()); namespaces.remove(element.getNamespacePrefix()); al.addAll(namespaces.values()); return Collections.unmodifiableList(al); }  static List<Namespace> getNamespacesInScope(Element element); static List<Namespace> getNamespacesInherited(Element element); static List<Namespace> getNamespacesIntroduced(Element element);  }
@Test public void testNamespaceInScope() throws Exception { String xml = "<?xml version=\"1.0\"?><root " + "xmlns:a=\"http: "xmlns:b=\"http: "xmlns:c=\"http: "xmlns:d=\"http: "<a:a/></root>"; Element xmle = Xml.loadString(xml, false); List<Namespace> inScope = NamespaceUtils.getNamespacesInScope(xmle); assertContains("Expected inscope namespace " + Namespace.NO_NAMESPACE, Namespace.NO_NAMESPACE, inScope); assertContains("Expected inscope namespace " + Namespace.getNamespace("a", "http: assertContains("Expected inscope namespace " + Namespace.getNamespace("b", "http: assertContains("Expected inscope namespace " + Namespace.getNamespace("c", "http: assertContains("Expected inscope namespace " + Namespace.getNamespace("d", "http: Element a = xmle.getChild("a", Namespace.getNamespace("a", "http: inScope = NamespaceUtils.getNamespacesInScope(a); assertContains("Expected inscope namespace " + Namespace.NO_NAMESPACE, Namespace.NO_NAMESPACE, inScope); assertContains("Expected inscope namespace " + Namespace.getNamespace("a", "http: assertContains("Expected inscope namespace " + Namespace.getNamespace("b", "http: assertContains("Expected inscope namespace " + Namespace.getNamespace("c", "http: assertContains("Expected inscope namespace " + Namespace.getNamespace("d", "http: }