Java Utililty Methods XML Child Element By QName

List of utility methods to do XML Child Element By QName

Description

The list of methods to do XML Child Element By QName are organized into topic(s).

Method

ElementgetChildElement(Element doc, QName elementQName)

Get an child element from the parent element given its QName

First an attempt to get the element based on its namespace is made, failing which an element with the localpart ignoring any namespace is returned.

NodeList nl = doc.getElementsByTagNameNS(elementQName.getNamespaceURI(), elementQName.getLocalPart());
if (nl.getLength() == 0) {
    nl = doc.getElementsByTagNameNS("*", elementQName.getLocalPart());
    if (nl.getLength() == 0)
        nl = doc.getElementsByTagName(elementQName.getPrefix() + ":" + elementQName.getLocalPart());
    if (nl.getLength() == 0)
        return null;
return (Element) nl.item(0);
ElementgetChildElement(Node parent, QName childNamespace)
get Child Element
if (parent != null) {
    NodeList children = parent.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (isElement(child) && matches(child, childNamespace.getLocalPart(), childNamespace)) {
            return (Element) child;
return null;
ElementgetChildElementOrNull(QName qName, Element element)
get Child Element Or Null
List<Element> elements = getChildElements(qName, element);
if (elements.isEmpty()) {
    return null;
if (elements.size() > 1) {
    throw new IllegalStateException(String.format(
            "Required qualified element %s is declared more than once: %d", qName, elements.size()));
return elements.get(0);
ListgetChildElements(QName qName, Element element)
get Child Elements
NodeList list = element.getElementsByTagNameNS(qName.getNamespaceURI(), qName.getLocalPart());
List<Element> elements = new ArrayList<>();
if (list == null || list.getLength() <= 0) {
    return elements;
for (int i = 0; i < list.getLength(); i++) {
    elements.add((Element) list.item(i));
return elements;
ListgetChildElementsAsListIntern(Node node, QName nodeName, boolean recursive)
get Child Elements As List Intern
List<Element> list = new LinkedList<Element>();
NodeList nlist = node.getChildNodes();
for (int i = 0; i < nlist.getLength(); i++) {
    Node child = nlist.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
        search(list, (Element) child, nodeName, recursive);
return list;
ListgetChildElementsIntern(final Node node, final QName nodeName, final boolean recurse)
get Child Elements Intern
final ArrayList<Element> list = new ArrayList<Element>();
if (node == null) {
    return list;
final NodeList nlist = node.getChildNodes();
for (int i = 0; i < nlist.getLength(); i++) {
    final Node child = nlist.item(i);
    if (child.getNodeType() == Node.ELEMENT_NODE) {
...