1 package org.wamblee.xml;
3 import java.util.ArrayList;
6 import java.util.TreeMap;
8 import org.w3c.dom.Attr;
9 import org.w3c.dom.Element;
10 import org.w3c.dom.NamedNodeMap;
11 import org.w3c.dom.Node;
12 import org.w3c.dom.NodeList;
15 * Utility class for performing various operations on DOM trees.
17 public final class DOMUtility {
20 * Disabled constructor.
23 private DOMUtility() {
28 * Removes duplicate attributes from a DOM tree.
31 * Node to remove duplicate attributes from (recursively).
32 * Attributes of the node itself are not dealt with. Only the
33 * child nodes are dealt with.
35 public static void removeDuplicateAttributes(Node aNode) {
36 NodeList list = aNode.getChildNodes();
37 for (int i = 0; i < list.getLength(); i++) {
38 Node node = list.item(i);
39 if (node instanceof Element) {
40 removeDuplicateAttributes((Element) node);
41 removeDuplicateAttributes(node);
47 * Removes duplicate attributes from an element.
52 private static void removeDuplicateAttributes(Element aElement) {
53 NamedNodeMap attributes = aElement.getAttributes();
54 Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
55 List<Attr> attlist = new ArrayList<Attr>();
56 for (int i = 0; i < attributes.getLength(); i++) {
57 Attr attribute = (Attr) attributes.item(i);
58 if (uniqueAttributes.containsKey(attribute.getNodeName())) {
59 System.out.println("Detected duplicate attribute '"
60 + attribute.getNodeName() + "'");
62 uniqueAttributes.put(attribute.getNodeName(), attribute);
63 attlist.add(attribute);
65 // Remove all attributes from the element.
66 for (Attr att : attlist) {
67 aElement.removeAttributeNode(att);
69 // Add the unique attributes back to the element.
70 for (Attr att : uniqueAttributes.values()) {
71 aElement.setAttributeNode(att);