KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > converter > DOMUtils


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.geronimo.converter;
18
19 import org.w3c.dom.Element JavaDoc;
20 import org.w3c.dom.NodeList JavaDoc;
21 import org.w3c.dom.Node JavaDoc;
22
23 /**
24  * Some helper methods for reading DOM trees. Have I written this like 8 times or what?
25  *
26  * @version $Rev: 476049 $ $Date: 2006-11-16 23:35:17 -0500 (Thu, 16 Nov 2006) $
27  */

28 public class DOMUtils {
29     public static String JavaDoc getChildText(Element JavaDoc parent, String JavaDoc childName) {
30         NodeList JavaDoc list = parent.getElementsByTagName(childName);
31         if(list.getLength() > 1) {
32             throw new IllegalStateException JavaDoc();
33         } else if(list.getLength() == 0) {
34             return null;
35         }
36         Element JavaDoc child = (Element JavaDoc) list.item(0);
37         return getText(child);
38     }
39
40     public static String JavaDoc getText(Element JavaDoc element) {
41         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
42         NodeList JavaDoc list = element.getChildNodes();
43         boolean found = false;
44         for(int i=0; i<list.getLength(); i++) {
45             Node JavaDoc node = list.item(i);
46             if(node.getNodeType() == Node.TEXT_NODE) {
47                 buf.append(node.getNodeValue());
48                 found = true;
49             }
50         }
51         return found ? buf.toString() : null;
52     }
53 }
54
Popular Tags