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.
29 * @param aNode Node to remove duplicate attributes from (recursively).
30 * Attributes of the node itself are not dealt with. Only the child
31 * nodes are dealt with.
33 public static void removeDuplicateAttributes(Node aNode) {
34 NodeList list = aNode.getChildNodes();
35 for (int i = 0; i < list.getLength(); i++) {
36 Node node = list.item(i);
37 if ( node instanceof Element ) {
38 removeDuplicateAttributes((Element)node);
39 removeDuplicateAttributes(node);
45 * Removes duplicate attributes from an element.
46 * @param aElement Element.
48 private static void removeDuplicateAttributes(Element aElement) {
49 NamedNodeMap attributes = aElement.getAttributes();
50 Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
51 List<Attr> attlist = new ArrayList<Attr>();
52 for (int i = 0; i < attributes.getLength(); i++) {
53 Attr attribute = (Attr)attributes.item(i);
54 if ( uniqueAttributes.containsKey(attribute.getNodeName())) {
55 System.out.println("Detected duplicate attribute '" + attribute.getNodeName() + "'");
57 uniqueAttributes.put(attribute.getNodeName(), attribute);
58 attlist.add(attribute);
60 // Remove all attributes from the element.
61 for (Attr att: attlist) {
62 aElement.removeAttributeNode(att);
64 // Add the unique attributes back to the element.
65 for (Attr att: uniqueAttributes.values()) {
66 aElement.setAttributeNode(att);