Saturday 6 August 2011

Returns the first child element with the given name.

  

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

public class Utils {


  /**
   * <p>Returns the first child element with the given name. Returns
   * <code>null</code> if not found.</p>
   *
   @param parent parent element
   @param name name of the child element
   @return child element
   */
  public static Element getChildElementByName(Element parent, String name)
  {
      NodeList children = parent.getChildNodes();

      for(int i = 0; i < children.getLength(); i++) {
          Node node = children.item(i);
          if(node.getNodeType() == Node.ELEMENT_NODE) {
              Element element = (Elementnode;
              if(element.getTagName().equals(name)) {
                  return element;
              }
          }
      }

      return null;
  }

}

   
    
  

No comments:

Post a Comment