Java XML Child Element By QName getChildElement(Element doc, QName elementQName)

Here you can find the source of getChildElement(Element doc, QName elementQName)

Description

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.

License

Apache License

Parameter

Parameter Description
doc a parameter
elementQName a parameter

Declaration

public static Element getChildElement(Element doc, QName elementQName) 

Method Source Code

//package com.java2s;
/*//  w  w w. j  a v  a  2s  .c o m
 * JBoss, Home of Professional Open Source
 *
 * Copyright 2013 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.w3c.dom.Element;

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

public class Main {
    /**
     * <p> Get an child element from the parent element given its {@link QName} </p> <p> 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. </p>
     *
     * @param doc
     * @param elementQName
     *
     * @return
     */
    public static Element getChildElement(Element doc, QName elementQName) {
        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);
    }
}

Related

  1. getChildElement(Node parent, QName childNamespace)
  2. getChildElementOrNull(QName qName, Element element)
  3. getChildElements(QName qName, Element element)
  4. getChildElementsAsListIntern(Node node, QName nodeName, boolean recursive)