(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.This is useful for postprocessing the
29      * output of JTidy as a workaround for a bug in JTidy. 
30      * 
31      * @param aNode
32      *            Node to remove duplicate attributes from (recursively).
33      *            Attributes of the node itself are not dealt with. Only the
34      *            child nodes are dealt with.
35      */
36     public static void removeDuplicateAttributes(Node aNode) {
37         NodeList list = aNode.getChildNodes();
38         for (int i = 0; i < list.getLength(); i++) {
39             Node node = list.item(i);
40             if (node instanceof Element) {
41                 removeDuplicateAttributes((Element) node);
42                 removeDuplicateAttributes(node);
43             }
44         }
45     }
46
47     /**
48      * Removes duplicate attributes from an element.
49      * 
50      * @param aElement
51      *            Element.
52      */
53     private static void removeDuplicateAttributes(Element aElement) {
54         NamedNodeMap attributes = aElement.getAttributes();
55         Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
56         List<Attr> attlist = new ArrayList<Attr>();
57         for (int i = 0; i < attributes.getLength(); i++) {
58             Attr attribute = (Attr) attributes.item(i);
59             if (uniqueAttributes.containsKey(attribute.getNodeName())) {
60                 System.out.println("Detected duplicate attribute '"
61                         + attribute.getNodeName() + "'");
62             }
63             uniqueAttributes.put(attribute.getNodeName(), attribute);
64             attlist.add(attribute);
65         }
66         // Remove all attributes from the element.
67         for (Attr att : attlist) {
68             aElement.removeAttributeNode(att);
69         }
70         // Add the unique attributes back to the element.
71         for (Attr att : uniqueAttributes.values()) {
72             aElement.setAttributeNode(att);
73         }
74     }
75 }