Mega Code Archive

 
Categories / Java / XML
 

DOM Util

import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main {   public static String getChildText(Element parent, String childName) {     NodeList list = parent.getElementsByTagName(childName);     if (list.getLength() > 1) {       throw new IllegalStateException("Multiple child elements with name " + childName);     } else if (list.getLength() == 0) {       return null;     }     Element child = (Element) list.item(0);     return getText(child);   }   public static String getText(Element element) {     StringBuffer buf = new StringBuffer();     NodeList list = element.getChildNodes();     boolean found = false;     for (int i = 0; i < list.getLength(); i++) {       Node node = list.item(i);       if (node.getNodeType() == Node.TEXT_NODE) {         buf.append(node.getNodeValue());         found = true;       }     }     return found ? buf.toString() : null;   } }