(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 import sun.security.krb5.internal.ktab.l;
15
16 /**
17  * Utility class for performing various operations on DOM trees. 
18  */
19 public final class DOMUtility {
20         
21         /**
22          * Disabled constructor.
23          *
24          */
25         private DOMUtility() { 
26                 // Empty
27         }
28         
29         /**
30          * Removes duplicate attributes from a DOM tree. 
31          * @param aNode Node to remove duplicate attributes from (recursively).
32          *    Attributes of the node itself are not dealt with. Only the child
33          *    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          * @param aElement Element. 
49          */
50         private static void removeDuplicateAttributes(Element aElement) { 
51             NamedNodeMap attributes = aElement.getAttributes();
52             Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
53             List<Attr> attlist = new ArrayList<Attr>();
54             for (int i = 0; i < attributes.getLength(); i++) {
55                 Attr attribute = (Attr)attributes.item(i);
56                 if ( uniqueAttributes.containsKey(attribute.getNodeName())) {
57                         System.out.println("Detected duplicate attribute '" + attribute.getNodeName() + "'");
58                 }
59                 uniqueAttributes.put(attribute.getNodeName(), attribute);
60                 attlist.add(attribute);
61             }
62             // Remove all attributes from the element. 
63             for (Attr att: attlist) { 
64                 aElement.removeAttributeNode(att);
65             }
66             // Add the unique attributes back to the element. 
67             for (Attr att: uniqueAttributes.values()) {
68                 aElement.setAttributeNode(att);
69             }
70         }
71 }