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.This is useful for postprocessing the
29 * output of JTidy as a workaround for a bug in JTidy.
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.
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);
48 * Removes duplicate attributes from an element.
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() + "'");
63 uniqueAttributes.put(attribute.getNodeName(), attribute);
64 attlist.add(attribute);
66 // Remove all attributes from the element.
67 for (Attr att : attlist) {
68 aElement.removeAttributeNode(att);
70 // Add the unique attributes back to the element.
71 for (Attr att : uniqueAttributes.values()) {
72 aElement.setAttributeNode(att);