1 7 8 package org.jboss.media.util; 9 10 import org.w3c.dom.Element ; 11 import org.w3c.dom.NamedNodeMap ; 12 import org.w3c.dom.Node ; 13 import org.w3c.dom.NodeList ; 14 15 21 public class DOMUtils 22 { 23 public static Node findNode(Node node, String name) 24 { 25 if (node.getNodeName().equals(name)) 26 { 27 return node; 28 } 29 if (node.hasChildNodes()) 30 { 31 NodeList list = node.getChildNodes(); 32 int size = list.getLength(); 33 for (int i = 0; i < size; i++) 34 { 35 Node found = findNode(list.item(i), name); 36 if (found != null) 37 return found; 38 } 39 } 40 return null; 41 } 42 43 public static String getNodeAttribute(Node node, String name) 44 { 45 if (node instanceof Element ) 46 { 47 Element element = (Element ) node; 48 return element.getAttribute(name); 49 } 50 return null; 51 } 52 53 public void displayNode(Node root) 54 { 55 displayNode(root, 0); 56 } 57 58 public static void displayNode(Node node, int level) 59 { 60 indent(level); 61 System.out.print("<" + node.getNodeName()); 63 NamedNodeMap map = node.getAttributes(); 64 if (map != null) 65 { 66 int length = map.getLength(); 68 for (int i = 0; i < length; i++) 69 { 70 Node attr = map.item(i); 71 System.out.print( 72 " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\""); 73 } 74 } 75 Node child = node.getFirstChild(); 76 if (child != null) 77 { 78 System.out.println(">"); while (child != null) 80 { 81 displayNode(child, level + 1); 83 child = child.getNextSibling(); 84 } 85 indent(level); 86 System.out.println("</" + node.getNodeName() + ">"); 88 } 89 else 90 { 91 System.out.println("/>"); 92 } 93 } 94 95 private static void indent(int level) 96 { 97 for (int i = 0; i < level; i++) 98 { 99 System.out.print(" "); 100 } 101 } 102 } 103 | Popular Tags |