KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > media > util > DOMUtils


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7
8 package org.jboss.media.util;
9
10 import org.w3c.dom.Element JavaDoc;
11 import org.w3c.dom.NamedNodeMap JavaDoc;
12 import org.w3c.dom.Node JavaDoc;
13 import org.w3c.dom.NodeList JavaDoc;
14
15 /**
16  * DOM utils.
17  *
18  * @version <tt>$Revision: 1.1 $</tt>
19  * @author <a HREF="mailto:ricardoarguello@users.sourceforge.net">Ricardo Argüello</a>
20  */

21 public class DOMUtils
22 {
23    public static Node JavaDoc findNode(Node JavaDoc node, String JavaDoc name)
24    {
25       if (node.getNodeName().equals(name))
26       {
27          return node;
28       }
29       if (node.hasChildNodes())
30       {
31          NodeList JavaDoc list = node.getChildNodes();
32          int size = list.getLength();
33          for (int i = 0; i < size; i++)
34          {
35             Node JavaDoc found = findNode(list.item(i), name);
36             if (found != null)
37                return found;
38          }
39       }
40       return null;
41    }
42
43    public static String JavaDoc getNodeAttribute(Node JavaDoc node, String JavaDoc name)
44    {
45       if (node instanceof Element JavaDoc)
46       {
47          Element JavaDoc element = (Element JavaDoc) node;
48          return element.getAttribute(name);
49       }
50       return null;
51    }
52
53    public void displayNode(Node JavaDoc root)
54    {
55       displayNode(root, 0);
56    }
57
58    public static void displayNode(Node JavaDoc node, int level)
59    {
60       indent(level);
61       // emit open tag
62
System.out.print("<" + node.getNodeName());
63       NamedNodeMap JavaDoc map = node.getAttributes();
64       if (map != null)
65       {
66          // print attribute values
67
int length = map.getLength();
68          for (int i = 0; i < length; i++)
69          {
70             Node JavaDoc attr = map.item(i);
71             System.out.print(
72                " " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
73          }
74       }
75       Node JavaDoc child = node.getFirstChild();
76       if (child != null)
77       {
78          System.out.println(">"); // close current tag
79
while (child != null)
80          {
81             // emit child tags recursively
82
displayNode(child, level + 1);
83             child = child.getNextSibling();
84          }
85          indent(level);
86          // emit close tag
87
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