Java XML Element Get by Name getFirstElement(Element parent, String name)

Here you can find the source of getFirstElement(Element parent, String name)

Description

get the first element in the parent element that's named name or null if no such element exists

License

Open Source License

Declaration

public static Element getFirstElement(Element parent, String name) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from www  .  j a  v a  2s.c  o m
     * get the first element in the parent element that's named name or null if no such element exists
     */
    public static Element getFirstElement(Element parent, String name) {
        NodeList list = parent.getElementsByTagName(name);

        Node node = list.item(0);
        if (node == null) {
            //throw new RuntimeException("Malformed XML: No such node: " + name);
            return null;
        }

        if (!isElement(node)) {
            throw new RuntimeException("XML Parsing error: " + name + " is not an Element");
        }

        return (Element) node;
    }

    public static boolean isElement(Node n) {
        return (n.getNodeType() == Node.ELEMENT_NODE);
    }
}

Related

  1. getElementsByTagName(final Element parentElement, final String elementName)
  2. getElementsByTagNameCaseInsensitive( Document doc, final Set lowerCaseNames)
  3. getElementValue(Element parent)
  4. getElementValue(Element parent, String tagName)
  5. getElementValue(Element parent, String tagName)
  6. getFirstElementAtAnyDepthByNodeName(Element parent, String name)
  7. getFirstElementByName(Element parent, String name)
  8. getFirstElementByName(String name, Element parent)
  9. getFirstElementByTagName(Element parent, String tagName)