Utils { public static Map<String,Element> removeChildrenToMap(Element elem) { Map<String,Element> children = new LinkedHashMap<String,Element>(); for (Element child : DomUtil.getChildren(elem)) { String localName = DomUtil.getLocalName(child); Element prev = children.put(localName, child); if (prev != null) throw new IllegalStateException("duplicate child name: " + localName); elem.removeChild(child); } return children; }  static List<File> buildFileListFromStringList(List<String> sources); static List<File> buildFileList(List<File> sources); static List<String> extractClassesFromJar(File jarFile); static Map<String,Element> removeChildrenToMap(Element elem); static Element reconstruct(Element elem, String... childOrder); static Element reconstruct(Element elem, Map<String,Element> children, String... childOrder);  }
@Test public void testRemoveChildrenToMap() throws Exception { Document dom = element("root", element("c2"), element("c1"), element("c5"), element("c4"), element("c3")) .toDOM(); Element root = dom.getDocumentElement(); Map<String,Element> map = Utils.removeChildrenToMap(root); assertTrue("root no longer has children", DomUtil.getChildren(root).isEmpty()); assertEquals("child names, in order", Arrays.asList("c2", "c1", "c5", "c4", "c3"), new ArrayList<String>(map.keySet())); for (String name : map.keySet()) { assertEquals("mapping refers to correct element (" + name + ")", name, DomUtil.getLocalName(map.get(name))); } }
@Test public void testRemoveChildrenToMapWithNamespaces() throws Exception { Document dom = element("root", element("x", "c2"), element("x", "c1"), element("x", "c5"), element("x", "c4"), element("x", "c3")) .toDOM(); Element root = dom.getDocumentElement(); Map<String,Element> map = Utils.removeChildrenToMap(root); assertTrue("root no longer has children", DomUtil.getChildren(root).isEmpty()); assertEquals("child names, in order", Arrays.asList("c2", "c1", "c5", "c4", "c3"), new ArrayList<String>(map.keySet())); for (String name : map.keySet()) { assertEquals("mapping refers to correct element (" + name + ")", name, DomUtil.getLocalName(map.get(name))); } }
@Test(expected=IllegalStateException.class) public void testRemoveChildrenToMapWithDuplicates() throws Exception { Document dom = element("root", element("x", "c2"), element("x", "c1"), element("y", "c2")) .toDOM(); Element root = dom.getDocumentElement(); Utils.removeChildrenToMap(root); }