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;
14 import sun.security.krb5.internal.ktab.l;
17 * Utility class for performing various operations on DOM trees.
19 public final class DOMUtility {
22 * Disabled constructor.
25 private DOMUtility() {
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.
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);
47 * Removes duplicate attributes from an element.
48 * @param aElement Element.
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() + "'");
59 uniqueAttributes.put(attribute.getNodeName(), attribute);
60 attlist.add(attribute);
62 // Remove all attributes from the element.
63 for (Attr att: attlist) {
64 aElement.removeAttributeNode(att);
66 // Add the unique attributes back to the element.
67 for (Attr att: uniqueAttributes.values()) {
68 aElement.setAttributeNode(att);