Saturday 6 August 2011

Returns text value of a child element. Returns null if there is no child element found.

  
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Utils {
  public static String getElementText(Element element)
  {
      StringBuffer buf = new StringBuffer();

      NodeList children = element.getChildNodes();
      for(int i = 0; i < children.getLength(); i++) {
          Node node = children.item(i);
          if(node.getNodeType() == Node.TEXT_NODE ||
             node.getNodeType() == Node.CDATA_SECTION_NODE) {
              Text text = (Textnode;
              buf.append(text.getData().trim());
          }
      }

      return buf.toString();
  }


}

   
    
  

No comments:

Post a Comment