1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package com.mjh.dom;
27
28 import java.util.ArrayList;
29 import java.util.Iterator;
30
31 import org.w3c.dom.*;
32
33
41 public class DomUtil
42 {
43 public static NodeList getChildElements(Node node)
44 {
45 return getChildNodesOfType(node, Node.ELEMENT_NODE);
46 }
47
48 public static NodeList getChildElementsByTagName(Node node, String tagName)
49 {
50 ArrayList list = getChildNodesOfTypeAsList(node, Node.ELEMENT_NODE);
51 Iterator elements = list.iterator();
52
53 list = new ArrayList();
54
55 while (elements.hasNext())
56 {
57 Element element = (Element) elements.next();
58
59 if (element.getTagName().equals(tagName))
60 {
61 list.add(element);
62 }
63 }
64
65 return new DomUtil().new NodeListImpl(list);
66 }
67
68 public static Node getFirstChildElement(Node node)
69 {
70 return getFirstChildNodeOfType(node, Node.ELEMENT_NODE);
71 }
72
73 public static Node getFirstChildNodeOfType(Node node, int type)
74 {
75 NodeList list = node.getChildNodes();
76
77 node = null;
78
79 int length = list.getLength();
80
81 for (int i = 0; i < length; i++)
82 {
83 node = list.item(i);
84
85 if (node.getNodeType() == type)
86 {
87 break;
88 }
89 }
90
91 return node;
92 }
93
94 public static NodeList getChildNodesOfType(Node node, short type)
95 {
96 ArrayList list = getChildNodesOfTypeAsList(node, type);
97
98 return new DomUtil().new NodeListImpl(list);
99 }
100
101 private static ArrayList getChildNodesOfTypeAsList(Node node, short type)
102 {
103 ArrayList list = new ArrayList();
104 NodeList nodes = node.getChildNodes();
105
106 if (nodes != null)
107 {
108 int length = nodes.getLength();
109
110 for (int i = 0; i < length; i++)
111 {
112 node = nodes.item(i);
113
114 if (node.getNodeType() == type)
115 {
116 list.add(node);
117 }
118 }
119 }
120
121 return list;
122 }
123
124 public class NodeListImpl
125 implements NodeList
126 {
127 private ArrayList list;
128
129 public NodeListImpl(ArrayList al)
130 {
131 list = al;
132 }
133
134 public int getLength()
135 {
136 return list.size();
137 }
138
139 public Node item(int index)
140 {
141 return (Node) list.get(index);
142 }
143 }
144 }