checkstyle
[utils] / support / src / org / wamblee / xml / DOMUtility.java
1 package org.wamblee.xml;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Map;
6 import java.util.TreeMap;
7
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;
13
14 /**
15  * Utility class for performing various operations on DOM trees.
16  */
17 public final class DOMUtility {
18
19     /**
20      * Disabled constructor.
21      * 
22      */
23     private DOMUtility() {
24         // Empty
25     }
26
27     /**
28      * Removes duplicate attributes from a DOM tree.
29      * 
30      * @param aNode
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.
34      */
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);
42             }
43         }
44     }
45
46     /**
47      * Removes duplicate attributes from an element.
48      * 
49      * @param aElement
50      *            Element.
51      */
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() + "'");
61             }
62             uniqueAttributes.put(attribute.getNodeName(), attribute);
63             attlist.add(attribute);
64         }
65         // Remove all attributes from the element.
66         for (Attr att : attlist) {
67             aElement.removeAttributeNode(att);
68         }
69         // Add the unique attributes back to the element.
70         for (Attr att : uniqueAttributes.values()) {
71             aElement.setAttributeNode(att);
72         }
73     }
74 }