Java XML Child Element By QName getChildElementOrNull(QName qName, Element element)

Here you can find the source of getChildElementOrNull(QName qName, Element element)

Description

get Child Element Or Null

License

Open Source License

Declaration

public static Element getChildElementOrNull(QName qName, Element element) 

Method Source Code


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

import org.w3c.dom.*;
import javax.xml.namespace.QName;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static Element getChildElementOrNull(QName qName, Element element) {
        List<Element> elements = getChildElements(qName, element);
        if (elements.isEmpty()) {
            return null;
        }/*from   w  ww  . ja  v  a 2s. com*/
        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);
    }

    public static List<Element> getChildElements(QName qName, Element element) {
        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;
    }
}

Related

  1. getChildElement(Element doc, QName elementQName)
  2. getChildElement(Node parent, QName childNamespace)
  3. getChildElements(QName qName, Element element)
  4. getChildElementsAsListIntern(Node node, QName nodeName, boolean recursive)
  5. getChildElementsIntern(final Node node, final QName nodeName, final boolean recurse)