(no commit message)
[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          * @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. 
32          */
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);
40                 }
41             }
42         }
43         
44         /**
45          * Removes duplicate attributes from an element. 
46          * @param aElement Element. 
47          */
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() + "'");
56                 }
57                 uniqueAttributes.put(attribute.getNodeName(), attribute);
58                 attlist.add(attribute);
59             }
60             // Remove all attributes from the element. 
61             for (Attr att: attlist) { 
62                 aElement.removeAttributeNode(att);
63             }
64             // Add the unique attributes back to the element. 
65             for (Attr att: uniqueAttributes.values()) {
66                 aElement.setAttributeNode(att);
67             }
68         }
69 }